Let's say we have a class Fooand we want to create a list foosthat we can do as follows:
foo_list = [Foo()] * 3
Now, what if we do foo_list[0].x = 5? This statement sets the attribute xto all of the instances within the list !!!
When I found this, it blew my mind. The problem is that when we create such a list, it is obvious that python will first create an instance Foo, then an instance of the list, and then add the same object 3 times to it, but I really expected it to do something like this
foo_list = [Foo() for i in range(3)]
Is not it? Well, now I know that definitely this syntactic sugar cannot be used since 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] * 5and that doesn't really matter much to me in the case of python.
Does this syntax have any other really useful use case?
source
share