Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...