Jun-01-2022, 09:08 PM
(This post was last modified: Jun-01-2022, 09:08 PM by deanhystad.)
This is a generator. It will generate 3 empty lists.
For the second question:
This does something called "unpacking":
Unpacking works with an iterable. (1, 2, 3) is a tuple, and tuples are iterable. Generators are also iterable. That is why your code assigns different empty lists to a, b and c.
This assigns the same value to variables a, b and c:
([] for i in range(3))You could ask Python what it is.
thing = ([] in range(3)) print(thing)
Output:<generator object <genexpr> at 0x000002AA50964F90>
And we can test how many things it generates.thing = ([] for i in range(3)) while True: print(next(thing))
Output:[]
[]
[]
Traceback (most recent call last):
File "...", line 3, in <module>
print(next(thing))
StopIteration
As predicted the generator "generates" 3 empty lists and then raises a StopIteration exception.For the second question:
This does something called "unpacking":
a, b, c = (1, 2, 3)There are 3 items in the tuple (1, 2, 3) and there are three variables on the left side of the the assignment. The three items are "unpacked" and assigned to the three variables. a = 1, b = 2, c = 3.
Unpacking works with an iterable. (1, 2, 3) is a tuple, and tuples are iterable. Generators are also iterable. That is why your code assigns different empty lists to a, b and c.
This assigns the same value to variables a, b and c:
a = b = c = (1, 2, 3)It is like doing this:
c = (1, 2, 3) b = c a = bIn your code ([] for i in range(3)) is a generator. So doing "a = b = c = ([] for i in range(3)):" is like doing this:
c = ([] for i in range(3)) b = c a = bc cannot be assigned the three different lists from the generator, so Python assigns the generator to the variable a.