Reef
Reef

Reputation: 33

Logic of all() method for sets

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

Upvotes: 3

Views: 30

Answers (2)

Mark
Mark

Reputation: 92461

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('')

Upvotes: 4

Ironkey
Ironkey

Reputation: 2607

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

Upvotes: 0

Related Questions