Muhammad Waqar
Muhammad Waqar

Reputation: 879

Python - checking if an element is in two lists at the same time

In Python, to check if an element is in two lists, we do

if elem in list1 and elem in list2:

Can we do the following for this purpose?

if elem in (list1 and list2):

Upvotes: 11

Views: 44482

Answers (12)

asdfasdf
asdfasdf

Reputation: 45

I'm unsure when * became a thing, but it allows 'in' to work with nested lists

Lists = {
    'List 1': [
        '11',
        '12',
        '13',
        '14'
    ],
    'List 2': [
        '21',
        '22',
        '23',
        '24'
    ]
}

if '22' in [*Lists['List 1'],*Lists['List 2']]:
    print('found')
else:
    print('not found')

Upvotes: 0

Rusca8
Rusca8

Reputation: 612

You can use list comprehensions:

if all([element in l for l in [list1, list2]]):

...which I just found a way to expand for checking if multiple elements are in every list:

if all([all([x in l for x in [elem1, elem2]]) for l in [list1, list2]]):

I guess with only 2 lists and 2 elements you'd rather do two like the first one (and just write and in between), but if you some day need to check if 10 elements are in 4 lists, this may come in handy.

Upvotes: 0

Moss
Moss

Reputation: 357

The all() function can be used here:

list1 = [1, 2, 3]
list2 = [2, 4, 6]

if all(elem in list for list in [list1, list2]):
    print("elem appears in both list1 and list2")

Upvotes: 2

Aaron de Windt
Aaron de Windt

Reputation: 17728

The shortest code to do this is to just concatenate the two lists into one by adding them and then checking, so like this.

a = [1, 2, 3]
b = [4, 5, 6]

print(1 in a + b)
print(5 in a + b)
print(9 in a + b)

However this isn't really efficient since it will create a new list with all of the elements in a and b. A more efficient way of doing this is to use the chain iterator from itertools.

from itertools import chain

a = [1, 2, 3]
b = [4, 5, 6]

print(1 in chain(a, b))
print(5 in chain(a, b))
print(9 in chain(a, b))

And if necessary it's also easy to add more lists or even a list of lists.

from itertools import chain

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

print(1 in a + b + c)
print(5 in a + b + c)
print(9 in a + b + c)

print(1 in chain(a, b, c))
print(5 in chain(a, b, c))
print(10 in chain(a, b, c))
print(9 in chain.from_iterable([a, b, c]))  # A list of lists

Upvotes: -1

Hallezgreat
Hallezgreat

Reputation: 1

You can do this:

for item in list1:
    if item in list2: 
        print item

Upvotes: 0

Sukrit Kalra
Sukrit Kalra

Reputation: 34531

No, the statement

if elem in (list1 and list2):

would not work for this specified purpose. What the Python interpreter does is first check list1, if found empty (i.e - False), it just returns the empty list (Why? - False and anything will always result in a false, so, why check further? ) and if not empty (i.e evaluated to True), it returns list2 (Why? - If first value is True, the result of the expression depends on the second value, if it is False, the expression evaluates to False, else, True.) , so the above code becomes if elem in list1 or if elem in list2 depending on your implementation. This is known as short circuiting.

The Wiki page on Short Circuiting might be a helpful read.

Example -

>>> list1 = [1, 2]
>>> list2 = [3, 4]
>>> list1 and list2
[3, 4]

>>> list1 = []
>>> list2 = [3, 4]
>>> list1 and list2
[]

Upvotes: 4

squiguy
squiguy

Reputation: 33380

What about using all?

all(elem in i for i in (list1, list2))

As @DSM pointed out, there is not need for zip.

Upvotes: 2

artdanil
artdanil

Reputation: 5082

For the code sample in question, boolean operator and will return one of the values tested (Truth Value Testing), so you will be testing only against one of them, and that does not guarantee the correct result.

>>> elem = 1
>>> list1 = [2, 3, 0]
>>> list2 = [1, 2, 3]
>>> if elem in (list1 and list2):
...     print "IN"
... 
>>> IN

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

No, you can't.

list1 and list2 will return the either the first empty list (because empty list is considered a falsy value) or if all lists were non-empty then rightmost list will be used.

for example:

>>> [1] and [1,2,3]
[1, 2, 3]
>>> [1,2] and []
[]
>>> [] and []
[]
>>> [] and [1,2]
[]
>>> [1] and [] and [1,2]
[]

Upvotes: 3

abarnert
abarnert

Reputation: 366213

No, you cannot.

list1 and list2 means "list1 if it's empty, list2 otherwise". So, this will not check what you're trying to check.

Try it in the interactive interpreter and see.


The simple way to do this is the code you already have:

if elem in list1 and elem in list2:

It works, it's easy to read, and it's obvious to write. If there's an obvious way to do something, Python generally tries to avoid adding synonyms that don't add any benefit. ("TOOWTDI", or "There should be one-- and preferably only one --obvious way to do it.")


If you're looking for an answer that's better in some particular way, instead of just different, there are different options depending on what you want.

For example, if you're going to be doing this check often:

elems_in_both_lists = set(list1) & set(list2)

Now you can just do:

if elem in elems_in_both_lists:

This is simpler, and it's also faster.

Upvotes: 18

Jon Clements
Jon Clements

Reputation: 142256

Nope, but you could write it as:

{elem}.intersection (list1, list2)

Upvotes: 3

kiddorails
kiddorails

Reputation: 13014

(list1 and list2) will evaluate boolean operation and return back last list - list2 if both have elements.
So, no, that won't work.

list1 = [1, 2, 3]
list2 = [2, 4, 5]

list1 and list2

gives [2, 4, 5]

list2 and list1

gives [1, 2, 3]

if 1 in (list1 and list2):
  print "YES"
else:
  print "NO"

Will give No

if 1 in (list2 and list1):
  print "YES"
else:
  print "NO"

will give "YES"

Upvotes: 0

Related Questions