Let's say we have a Foo
class and we want to instantiate a lists of foos
, which we can do as follows:
foo_list = [Foo()] * 3
Now what if we do foo_list[0].x = 5
? This statement will set the attribute x
to all of the instances inside the list!!!
When I found this it blew my mind. The problem is that when we create a list like that, apparently python will create the Foo
instance first, then the list instance, and then append the same object to it 3 times, but I really would expect it to do something like this:
foo_list = [Foo() for i in range(3)]
Wouldn't you too? Well, now I know that definitely this syntactic sugar can't be used as I wanted to use it, but then, what is it used for? The only thing I can think of is to create a list with an initial size like this: list = [None] * 5
, and that doesn't make much sense to me in the case of python.
Does this syntax have any other really useful use case?