Check if value exists in multiple lists

I would like to check if a value exists in each list.

The following returns Trueas expected, but seems non-pyphonic.

What is the correct / more elegant way to do this?

a = [1 ,2]
b = [1, 3]
c = [1, 4]
d = [2, 5]

False in [True if 1 in l else False for l in [a, b, c, d]  ]
+4
source share
1 answer

You can use a generatorall expression :

all(1 in x for x in (a, b, c, d))

Demo:

>>> a = [1 ,2]
>>> b = [1, 3]
>>> c = [1, 4]
>>> d = [2, 5]
>>> all(1 in x for x in (a, b, c, d))
False
>>> all(1 in x for x in (a, b, c))
True
>>>

In addition to being more readable, this solution is more efficient because it uses a lazy rating. He will check only as many elements as necessary to determine the result.

In addition, there was never a good reason:

True if 1 in l else False

- , in . :

1 in l

:

1 not in l
+11

Source: https://habr.com/ru/post/1569496/


All Articles