Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does all() in python work on empty lists

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?

like image 573
quirkystack Avatar asked Oct 26 '13 01:10

quirkystack


People also ask

How does empty list work in Python?

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.

How do you deal with an empty list in Python?

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.

Does an empty list equal none Python?

Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.

What is an empty list equal to in Python?

In Python, empty lists evaluate False , and non-empty lists evaluate True in boolean contexts.


1 Answers

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.

like image 199
OmnipotentEntity Avatar answered Oct 04 '22 03:10

OmnipotentEntity