Reputation: 65
I made a function and my result is a list:
[3, 3, 3]
Now I need to return a boolean value. If all of the elements are 2 or higher, I need to return True otherwise I need to return false. In this case it would be : True. ( Because all the elements are 3 and 3 > 2) Is there any code to do this quickly?
I tried to make a FOR - loop like:
for i in [3, 3, 3]: if i >= 2: return True else: return False
I think this is correct but I want to know if there is a faster method.
thanks in advance!
Upvotes: 0
Views: 143
Reputation: 46533
Make a generator (generator expression here) that yields booleans and pass it to all
function:
>>> all(x >= 2 for x in [3, 3, 3])
True
I see you posted your code, it's not correct as it will only check the first element of the list. You can fix it:
for i in your_list:
if i < 2:
return False # Return early
return True # if `i < 2` was False for all elements in the list, return True
Upvotes: 4
Reputation: 467
def areGreaterEqualThen2(lst):
if lst:
return lst[0] >= 2 and areGreaterEqualThen2(lst[1:])
return True
If you have to define your own function.
It also is a fast solution because if the first condition is false, the entire and
returns false.
Upvotes: 0
Reputation: 3584
a= [3, 3, 3]
b=[elem for elem in a if elem > 2]
print (a==b)
Output: True
or in a more condensed way
a= [3, 3, 3]
print([elem for elem in a if elem > 2]==a)
Output: True
Upvotes: 0