35

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()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zoomulator
  • 20,774
  • 7
  • 28
  • 32
  • 1
    Can somebody edit this so that "my_squence" is spelled consistently throughout? my_squence != my_sequence Thanks. – Sean Jan 01 '09 at 23:55

4 Answers4

63

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Autoplectic
  • 7,566
  • 30
  • 30
14

Do you mean

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

?

Edit: Changed to is. Slightly faster.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • @ 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. Jan 01 '09 at 22:05
  • Both any and all are efficient, meaning the stop iterating once they find a True or False value respectively. – tzot Jan 01 '09 at 23:08
  • 1
    @JV: all == and any != are the same over an average number of cases. – S.Lott Jan 01 '09 at 23:30
11

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.

oHo
  • 51,447
  • 27
  • 165
  • 200
tzot
  • 92,761
  • 29
  • 141
  • 204
1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MacL3an
  • 36
  • 2