I have a couple of lists which vary in length, and I would like to compare each of their items with an integer, and if any one of the items is above said integer, it breaks
Don't use list
as a variable name, it shadows the builtin list()
. There is a builtin function called any which is useful here
if any(x>70 for x in the_list):
The part inbetween the (
and )
is called a generator expression
Well, I'd probably do it using the generator expression, but since no one else has suggested this yet, and it doesn't have an (explicit) nested loop:
>>> lol = [[1,2,3],[4,40],[10,20,30]]
>>>
>>> for l in lol:
... if max(l) > 30:
... continue
... print l
...
[1, 2, 3]
[10, 20, 30]
If you're using python 2.5 or greater, you can use the any() function with list comprehensions.
for list in listoflists:
if any([i > 70 for i in list]):
continue
You can shorten it to this :D
for good_list in filter(lambda x: max(x)<=70, listoflists):
# do stuff
Using the builtin any
is the clearest way. Alternatively you can nest a for loop and break out of it (one of the few uses of for-else construct).
for lst in listoflists:
for i in lst:
if i > 70:
break
else:
# rest of your code
pass
You can use the built-in function any like this:
for list in listoflists:
if any(x < 70 for x in list):
continue
The any
function does short-circuit evaluation, so it will return True
as soon as an integer in the list is found that meets the condition.
Also, you should not use the variable list
, since it is a built-in function.