Why is a generator expression called a expression?

DL Neil PythonList at DancesWithMice.info
Mon Apr 20 06:01:10 EDT 2020


On 20/04/20 9:19 PM, Chris Angelico wrote:
> 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. :)

and, the () are not integral to a tuple. They form a 'parenthesised 
form". In other words they are delimiters - particularly useful if an 
expression needs to span multiple lines of code!

It is the comma-separated "list of expressions" which defines a tuple, 
ie the parentheses are somewhat optional and certainly not 
in-and-of-themselves, a definition, eg

a, b = 1, 2

Which is why a single element/expression tuple must be expressed with a 
comma. Yet, things become slightly confusing when an empty pair of 
parentheses defines an empty tuple.


You will find these definitions (and so much more) in the Python 
Reference Manual amongst the Python docs.
-- 
Regards =dn


More information about the Python-list mailing list