The Python Oracle

How to check if a value in one list is in another list with a one-liner for an if statement in Python if I'm not using sets?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 How To Check If A Value In One List Is In Another List With A One-Liner For An If Statement In Pytho
00:48 Accepted Answer Score 17
01:14 Answer 2 Score 6
01:47 Answer 3 Score 3
02:14 Thank you

--

Full question
https://stackoverflow.com/questions/4509...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #list

#avk47



ACCEPTED ANSWER

Score 17


You can us an any(..) builtin function with a generator expression:

any(e in list2 for e in list1)

So this will check if there is at least one element that occurs in both lists.

Note however that this will result in a worst-case O(n2) algorithm. If the elements are hashable for instance, and you can use a set, we can make it an O(n) average-case algorithm.




ANSWER 2

Score 6


You could also do

set(list1).intersection(list2)

to get the set of elements that occur in both; the length of the set is 0 if there's no intersection, otherwise positive. You can treat this set as a boolean, since Python evaluates empty sets to False and nonempty sets to True.

if set(list1).intersection(list2):
    print ('Lists have elements in common')
else: 
    print ('No elements in common')

Runtime is O(n) average-case, O(n^2) worst-case: https://wiki.python.org/moin/TimeComplexity




ANSWER 3

Score 3


Supose we have this lists:

list1 = ['bar', 'foo', 'qwerty', 9, 1]
list2 = [1, 2, 3, 'foo']

If we want to see the repeated values:

[i for i in list1 if i in list2]

The input:

['foo', 1]

If we want True false:

(map(lambda each: each in list1, list2))

The input:

[True, False, False, True]

The input is checking list2, the first value '1' exists in list1 and the last 'foo' too.