On Sat, Mar 06, 2021 at 08:21:47AM +0200, Frank Millman wrote:
> [...]
> 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.
> 
> TIA for any insights.
> 
> Frank Millman

In your first example, a certain element is appended to s each time in
the loop. But in your second example, the generator first traverses all
the elements, and then generates an iterable object, you are trying to
append this object to s.

Let's look at a simpler but more certain example:

a = [1, 2, 3]
s = []
for n in a:
    s.append(n)
# Result: 
# len(s) == 3
# s == [1, 2, 3]

a = [1, 2, 3]
s = []
g = (n for n in a)
s.append(g)
# Result:
# len(s) == 1
# list(s[0]) == [1, 2, 3]

If you want to get the same result in the above two cases, just replace
append with extend.
list.extend() can accept an iterable object as input, and then append all
the elements to the original list.

-- 
OpenPGP fingerprint: 3C47 5977 4819 267E DD64  C7E4 6332 5675 A739 C74E

Attachment: signature.asc
Description: PGP signature

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to