I am referring to the following python code
all(a==2 for a in my_list)
I expect the above code to return True if all the elements in my_list are 2. but when I make my_list empty and run it as
my_list = []
all(a==2 for a in my_list)
it returns True as well. I am confused with this behaviour. Is it not supposed to return False as there is no element in my_list with value 2?
You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.
Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.
Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.
In Python, empty lists evaluate False , and non-empty lists evaluate True in boolean contexts.
It's true because for every element in the list, all 0 of them, they all are equal to 2.
You can think of all being implemented as:
def all(list, condition):
for a in list:
if not condition(a):
return false
return true
Whereas any is:
def any(list, condition):
for a in list:
if condition(a):
return true
return false
That is to say, all
is innocent until proven guilty, and any
is guilty until proven innocent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With