Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "all" function with conditional generator expression returning True. Why?

Can anyone help me understand why the following Python script returns True?

x = ''
y = all(i == ' ' for i in x)
print(y)

I imagine it's something to do with x being a zero-length entity, but cannot fully comprehend.

like image 557
chrsmrrtt Avatar asked Feb 15 '23 01:02

chrsmrrtt


2 Answers

all() always returns True unless there is an element in the sequence that is False.

Your loop produces 0 items, so True is returned.

This is documented:

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

Emphasis mine.

Similarly, any() will always return False, unless an element in the sequence is True, so for empty sequences, any() returns the default:

>>> any(True for _ in '')
False
like image 180
Martijn Pieters Avatar answered Apr 28 '23 10:04

Martijn Pieters


As the documentation states, what all does is:

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

like image 37
BrenBarn Avatar answered Apr 28 '23 10:04

BrenBarn