Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Check if element is not in two lists?

I need to check if an element is not in two lists. I currently have:

if ele not in lista:
    if ele not in listb:
        do stuff

Using the following code did not work. Is there a more efficient way to accomplish the above in python?

if ele not in lista and listb:
    do stuff
like image 804
user2084666 Avatar asked Mar 31 '13 02:03

user2084666


2 Answers

if ele not in lista and ele not in listb:
    # do stuff

or

if ele not in lista + listb:
    # do stuff

but the second option will involve list concatenation which could potentially cause memory issues with large lists, also it will have to go through the list twice. To remedy this you could use itertools:

from itertools import chain
if ele not in chain(lista, listb):
    # do stuff

If you are going to be constantly checking for membership, you want to be using a set which has O(1) (amortized) lookup instead of O(n) for lists.

eg.

items_set = set(chain(lista, listb))
if ele in items_set:  # this membership check will be a lot faster
    # do stuff
like image 90
jamylak Avatar answered Sep 19 '22 01:09

jamylak


if ele not in lista and ele not in listb:
like image 37
Jorge Israel Peña Avatar answered Sep 18 '22 01:09

Jorge Israel Peña