Logic of all() method for sets

Viewed 27

The all() method returns True if all elements in a set are true. What's the logic behind the following contradictory results:

Result 1:

D = {'0', '000', ''}    
all(D)

#output: 
False

Result 2:

for e in D:    
    print(all(e))

#output:
True
True
True
2 Answers

The python docs are clear here:

all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty).

In the second case you are basically asking:

all('')

which is an empty iterable so it is True.

In the first case you are asking if each item in the set is boolean True, and the empty string is not truthy. It basically comes down to:

all('') != bool('')

From what i can see the empty string is interpreted as false

D = {'0', '000', 'x'}    
print(all(D))
True

vs

D = {'0', '000', ''}    
print(all(D))
False
Related