Reputation: 300
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 the for loop that it is in.
for list in listoflists:
if {anyiteminlist} > 70:
continue #as in skip to next list
{rest of code here}
Basically, I need to say: "If anything in this list is above 70, continue the loop with the next list"
Upvotes: 7
Views: 61562
Reputation: 22791
You can shorten it to this :D
for good_list in filter(lambda x: max(x)<=70, listoflists):
# do stuff
Upvotes: 1
Reputation: 353499
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]
Upvotes: 3
Reputation: 39000
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
Upvotes: 0
Reputation: 304463
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
Upvotes: 23
Reputation: 67163
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.
Upvotes: 1
Reputation: 159
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
Upvotes: 0