If all in list == something

Question:

Using Python 2.6, is there a way to check if all the items of a sequence equals a given value, in one statement?

[pseudocode]
my_sequence = (2,5,7,82,35)

if all the values in (type(i) for i in my_sequence) == int:
     do()

Instead of, say:

my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
    if type(i) is not int:
        all_int = False
        break

if all_int:
    do()
Asked By: Zoomulator

||

Answers:

Do you mean

all( type(i) is int for i in my_list )

?

Edit: Changed to is. Slightly faster.

Answered By: S.Lott

Use:

all( type(i) is int for i in lst )

Example:

In [1]: lst = range(10)
In [2]: all( type(i) is int for i in lst )
Out[2]: True
In [3]: lst.append('steve')
In [4]: all( type(i) is int for i in lst )
Out[4]: False

[Edit]. Made cleaner as per comments.

Answered By: Autoplectic

I would suggest:

if all(isinstance(i, int) for i in my_list):

all and any first appeared in 2006 with Python 2.5 (feature implemented by Raymond Hettinger).
If you’re using an older version of Python, the links provide sample implementations.

I also suggest using isinstance since it will also catch subclasses of int.

Answered By: tzot

For the sake of completeness I thought I would add the fact that NumPy’s ‘all’ is different from the built-in ‘all’. If for example running Python through Python(x,y), NumPy is loaded automatically (and cannot be unloaded as far as I know), so when trying to run the above code it produces rather unexpected results:

>>> if (all(v == 0 for v in [0,1])):
...     print 'this should not happen'
... this should not happen

More information on this is in Stack Overflow question numpy all differing from builtin all. As a solution you can either surround the generator with brackets to produce a list:

>>> all( [v == 0 for v in [0,1]] )
False

Or call the built-in function explicitly:

>>> __builtins__.all(v == 0 for v in [0,1,'2'])
False

I found a way to stop Spyder from importing NumPy per default:
Spyder default module import list

Answered By: MacL3an
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.