Randize
Randize

Reputation: 121

Possible to simplify finding if an element exist in multiple lists?

This is my Python code, it's usable but... I'm sure there a way to simplify this long code.

if partialAnswer in primaryTrees or partialAnswer in secondaryTrees or partialAnswer in tertiaryTrees:

Anyone have a good answer for this?

Upvotes: 0

Views: 52

Answers (5)

Steve Jessop
Steve Jessop

Reputation: 279255

As I feel is obligatory for Python questions involving collections, here's an answer based on itertools:

 if partialAnswer in itertools.chain(primaryTrees, secondaryTrees, tertiaryTrees)

Beware though, that this answer becomes inefficient (compared with your original code) if the trees change to a different collection that implements in by doing something faster than a linear search.

Upvotes: 3

Ben
Ben

Reputation: 2472

You can use sum. It will be less efficient, but looks simpler.

if partialAnswer in sum(primaryTrees, secondaryTrees, tertiaryTrees, []):

Upvotes: 1

jwodder
jwodder

Reputation: 57480

partialAnswer is in at least one of those lists if & only if it's in the concatenation of the lists, so:

if partialAnswer in primaryTrees + secondaryTrees + tertiaryTrees:

Upvotes: 1

voithos
voithos

Reputation: 70552

Use any():

trees = (primaryTrees, secondaryTrees, tertiaryTrees)
if any(partialAnswer in tree for tree in trees):
    ...

In essence, any() is equivalent to a series of or operations on an iterable of booleans, while its cousin all() is equivalent to a series of and operations.

Upvotes: 1

user2555451
user2555451

Reputation:

You can use any and a generator expression:

if any(partialAnswer in x for x in (primaryTrees, secondaryTrees, tertiaryTrees)):

See a demonstration below:

>>> listA = [1, 2, 3]
>>> listB = [4, 5, 6]
>>> listC = [7, 8, 9]
>>> n = 9
>>> any(n in x for x in (listA, listB, listC))
True
>>> n = 4
>>> any(n in x for x in (listA, listB, listC))
True
>>> n = 0
>>> any(n in x for x in (listA, listB, listC))
False
>>>

Upvotes: 3

Related Questions