Why is a generator expression called a expression?

Chris Angelico rosuav at gmail.com
Mon Apr 20 05:19:31 EDT 2020


On Mon, Apr 20, 2020 at 6:51 PM Veek M <veek at dont-use-this.com> wrote:
>
> The docs state that a expression is some combination of value, operator,
> variable and function. Also you cannot add or combine a generator
> expression with a value as you would do with 2 + 3 + 4. For example,
> someone on IRC suggested this
> all(a == 'a' for a in 'apple') but
>
> 1. all is a function/method
> 2. so (whatever) in this case is a call but obviously it works so it must
> be a generator object as well.. so.. how does 'all' the function object
> work with the generator object that's being produced?
>
> I can't for example do min 1,2,3 but i can do min (1,2,3) and the () are
> not integral to a tuple - therefore one could argue that the () are part
> of the call - not so with a generator Expression where the () are
> integral to its existence as an object.
>
> Could someone clarify further.

Short answer: An expression is anything that you can evaluate - that
is, anything where you can figure out its value. "1 + 1" is an
expression that has the value 2, but a 'for' loop doesn't have a
value, so it's not an expression.

In the case of a genexp, the expression has a value which is a
generator object. When you pass that to all(), it takes it and then
iterates over it, because that's one of the things you can do with a
generator object. :)

ChrisA


More information about the Python-list mailing list