0
a=[1,2,5]
b=[3,4]
x=8
res= (x not in a) and (x not in b)   #True

But what is the nice and fastest way to check it?

Mandeep Thakur
  • 655
  • 1
  • 10
  • 23
Dork
  • 1,816
  • 9
  • 29
  • 57
  • 1
    That's pretty much it. – TigerhawkT3 Jan 24 '17 at 05:27
  • 1
    I mean, if you wanted, you could use `all`, but for just two lists your current approach is already very readable. – TigerhawkT3 Jan 24 '17 at 05:28
  • 1
    If you have a lot of values, and your lists are fairly large, then you should convert your lists to sets. – Akavall Jan 24 '17 at 05:29
  • The way you have written it should be fast enough. – Burhan Khalid Jan 24 '17 at 05:30
  • Thanks. I'm new and I thought python may have some nice magic syntaxis for this like in many other cases) – Dork Jan 24 '17 at 05:33
  • Possible duplicate of [How can I compare two lists in python and return matches](http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches) – l'L'l Jan 24 '17 at 05:37
  • 1
    The way to do it is to realize that a list membership check is O(n) whereas it is O(1) for sets; if order is not important, use sets instead. – Antti Haapala -- Слава Україні Jan 24 '17 at 05:37
  • If `a` and `b` are large, and you really want to check that `x` isn't in _both_ `a` and `b` rather than in _either_ `a` or `b`, then it may be more efficient to create a set of the intersection of `a` and `b`, especially if you have lots of `x`s to test. – PM 2Ring Jan 24 '17 at 06:21

3 Answers3

1

While your solution is perfectly fine and readable, you can make it more generic by allowing a variable number of list and checking if a given element is in any of them by wrapping it in a function:

>>> def not_in_any(*lists, key=None):
        for lst in lists:
            if key in lst:
                return False
        return True

>>> not_in_any([2, 5, 7], [8, 9, 23], [34, 56, 78], [32, 91, 6], key=32)
False
>>> not_in_any([2, 5, 7], [8, 9, 23], [34, 56, 78], [31, 91, 6], key=32)
True
>>> 

Note however that Python already provides a built in function - any() which already provides the behavior of the for-loop in our function:

def not_in_any(key=None, *lists):
    not any(key in l for l in lists)
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0
a=[1,2,5]
b=[3,4]
x=8
all(x not in i for i in (a, b))

OR:

from itertools import chain
x not in chain(a, b)
宏杰李
  • 11,820
  • 2
  • 28
  • 35
-1

Other approach is concat and check:-

a=[1,2,5]
b=[3,4]
x=8
res= x not in a+b  #True
Rakesh Kumar
  • 4,319
  • 2
  • 17
  • 30