How to check if one of the following items is in a list?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 Question
00:30 Accepted answer (Score 345)
00:47 Answer 2 (Score 306)
01:02 Answer 3 (Score 34)
01:15 Answer 4 (Score 20)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/7402...
Answer 1 links:
[Tobias' solution]: https://stackoverflow.com/a/740359/45183...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 Question
00:30 Accepted answer (Score 345)
00:47 Answer 2 (Score 306)
01:02 Answer 3 (Score 34)
01:15 Answer 4 (Score 20)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/7402...
Answer 1 links:
[Tobias' solution]: https://stackoverflow.com/a/740359/45183...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 360
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])
Both empty lists and empty sets are False, so you can use the value directly as a truth value.
ANSWER 2
Score 331
I was thinking of this slight variation on Tobias' solution:
>>> a = [1,2,3,4]
>>> b = [2,7]
>>> any(x in a for x in b)
True
ANSWER 3
Score 36
Maybe a bit more lazy:
a = [1,2,3,4]
b = [2,7]
print any((True for x in a if x in b))
ANSWER 4
Score 20
Think about what the code actually says!
>>> (1 or 2)
1
>>> (2 or 1)
2
That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:
def or(x, y):
if x: return x
if y: return y
return False
In the first example, x == 1 and y == 2. In the second example, it's vice versa. That's why it returns different values depending on the order of them.