David542
David542

Reputation: 110093

See if List only has certain values

Given a list:

x = [1,2,1,1,1,2,1]

Is there a one-liner to see if the list only contains the specified values and nothing else? For example:

x([1,2]) = True
x([1,]) = False
x([1,2,3]) = False

Upvotes: 0

Views: 1900

Answers (3)

Alex Martelli
Alex Martelli

Reputation: 881507

An alternative to set suggested in other questions, which can be faster in some cases in which it fails:

all(y in (1, 2) for y in x)

It can sometimes be faster because all "fails fast" -- it bails out (doesn't keep looping) as soon as it finds one item that's false.

As for speed,

$ python -mtimeit -s'x=[1,2,1,1,1,2,1];check=(1,2)' 'all(y in check for y in x)'
1000000 loops, best of 3: 1.03 usec per loop
$ python -mtimeit -s'x=[1,2,1,1,1,2,1];check=set((1,2))' 'all(y in check for y in x)'
1000000 loops, best of 3: 1.01 usec per loop

(timing difference "in the noise"). The suggested use of sets per the other answers, if a killer bug present in the original versions of both is fixed, is indeed faster:

$ python -mtimeit -s'x=[1,2,1,1,1,2,1];check=set((1,2))' 'set(x)<=check'
1000000 loops, best of 3: 0.425 usec per loop

The killer bug is that said original versions, for both answers (now corrected in edits), used == instead of <= -- so they checked that the items of x are exactly the same as those of check, rather than, as needed to satisfy your specs, being a subset thereof (one of your examples required True for x and [1,2,3] and both those original versions would have failed there).

Upvotes: 5

jme
jme

Reputation: 20695

It looks like you want to see if the elements of a list come from some set. If that's the case, you can convert to a set and use issubset:

>>> x = set([1,2,1,1,1,2,1])
>>> x.issubset([1,2])
True
>>> x.issubset([1])
False
>>> x.issubset([1,2,3])
True

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251365

You can check if, e.g., set(x) <= set([1, 2]). (You can use {1, 2} for set([1, 2]) in Python 2.7 and up.)

Upvotes: 4

Related Questions