Reputation: 2472
Suppose I have a list of numbers mylist
and that I would like execute some code if all the elements of mylist
are greater than 10. I might try
if mylist[0] > 10 and mylist[1] > 10 and ... :
do something
but this is obviously very cumbersome. I was wondering if Python has a way of compressing multiple conditions in an if statement. I tried
if mylist[i] > 10 for i in range(len(mylist)):
do something
but this returned an error.
I am using Python 3.4.
Upvotes: 2
Views: 716
Reputation: 76204
Your attempt is pretty close. You just needed the all
function to examine the results of the expression.
if all(mylist[i] > 10 for i in range(len(mylist))):
do something
Incidentally, consider iterating over the items of the list directly, rather than its indices.
if all(item > 10 for item in mylist):
Upvotes: 7
Reputation: 19770
The answer is all
:
if all(item > 10 for item in mylist):
do something
Upvotes: 0