views:

313

answers:

3

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()
+11  A: 

Do you mean

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

?

Edit: Changed to is. Slightly faster.

S.Lott
@ S.Lott: thinking negation, will `any( type(i) != int for i in my_lst )` be more efficient? or the same over an average number of cases?
JV
Both any and all are efficient, meaning the stop iterating once they find a True or False value respectively.
ΤΖΩΤΖΙΟΥ
@JV: all == and any != are the same over an average number of cases.
S.Lott
+10  A: 

how about:

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

Autoplectic
you can leave out the list comprehension! a simple generator expression will be sufficient (and more efficient).
hop
@hop: can comments be voted up? like yours. :)
JV
When comparing types, always use "is"!
Benjamin Peterson
+4  A: 

I would suggest:

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

all and any first appeared in Python 2.5. 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.

ΤΖΩΤΖΙΟΥ