2

Is there a way in Python to force to generate a new object when creating a list?

Assume I have a class Test of which I want to store 5 objects in a list.
I use the following code to generate the list:

myList = [Test()] * 5

With this code python creates only 1 Object which is stored 5 times.

Of course I could use a for-loop to generate the list. But in my real program this would blow up the code extremly, because I have about 30 lists, which are partly nested in another List.

So Is there a fast way (maybe a one-liner) to force python to generate a new Object in each entry?

0xAffe
  • 1,156
  • 1
  • 13
  • 29

1 Answers1

9

Use a list comprehension to execute an expression more than once:

myList = [Test() for _ in range(5)]

Since this would ignore the range()-produced index, I named the for loop target _ to signal the variable is ignored; this is just a naming convention.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you! this works. For my nested list I can use `myList = [[Test() for _ in range(5)] for _ in range(2)]` What exaclty means the `_` , by the way? – 0xAffe Mar 03 '15 at 12:32
  • 2
    @0xAffe It is an informal way to say "I am not going to use this variable" https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python – Cory Kramer Mar 03 '15 at 12:35
  • 1
    @0xAffe: it is just convention, just like naming the first argument of a method `self`. – Martijn Pieters Mar 03 '15 at 12:37
  • @0xAffe, in some IDEs, it will save you from warnings about unused variables – volcano Mar 03 '15 at 12:45