Python Forum

Full Version: Syntax when initializing empty lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I have two questions with regard to initializing empty lists. This works:

list_a, list_b, list_c = ([] for i in range(3))
What exactly do the parentheses mean on the right? Without them I get a syntax error. With them, though, I don't recognize what kind of statement it makes. For example, it's not a list comprehension as that would be in brackets.

Second, on the left if I use equals signs instead of commas, then I get all three labels pointing to a generator object. Why?
This is a generator. It will generate 3 empty lists.
([] 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 = b
In 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 = b
c cannot be assigned the three different lists from the generator, so Python assigns the generator to the variable a.
Thanks for the detailed explanation, Dean!