On 2021-03-06 8:21 AM, Frank Millman wrote:
Hi all
This is purely academic, but I would like to understand the following -
>>>
>>> a = [('x', 'y')]
>>>
>>> s = []
>>> for b, c in a:
... s.append((b, c))
...
>>> s
[('x', 'y')]
This is what I expected.
>>>
>>> s = []
>>> s.append(((b, c) for b, c in a))
>>> s
[<generator object <genexpr> at 0x0000019FC3F863C0>]
>>>
I expected the same as the first one.
I understand the concept that a generator does not return a value until
you call next() on it, but I have not grasped the essential difference
between the above two constructions.
Thanks, Alan and Ming.
I think I have got it now.
In my first example, a 'for' loop both creates an iterable object *and*
iterates over it.
In my second example, a generator expression creates an iterable object,
but does nothing with it until asked.
Changing 'append' to 'extend' has the effect of iterating over the
generator expression and appending the results.
Frank
--
https://mail.python.org/mailman/listinfo/python-list