1

I am trying to make a list of lists in a one-lined efficient manner, but I can't come up with any way to avoid having references. This is what I have tried so far, obviously unsuccessfully:

>>> test=[[None]*3][:]*3
>>> test
[[None, None, None], [None, None, None], [None, None, None]]
>>> test[0][0]=0
>>> test
[[0, None, None], [0, None, None], [0, None, None]]
>>> 

This is not what I want to happen. What I want is for 0 to be the first item of only the first list. How can I do this?

ThisIsAQuestion
  • 1,887
  • 14
  • 20

1 Answers1

5

Use a list comprehension:

test = [[None] * 3 for _ in range(3)]

(Note the _ is just a convention for output that is irrelevant, in this case 0, 1, and 2)

mhlester
  • 22,781
  • 10
  • 52
  • 75
  • Thanks. I was trying to get it down into one line so I was avoiding for loops. I forgot that they can be compressed into one line like this. By the way does using _ instead of a variable not store the number? – ThisIsAQuestion Jan 28 '14 at 20:53
  • Exactly so. To further clarify your note: the `_` does not carry any special meaning to the interpreter -- it's entirely for readability's sake. It lets any future programmer know that we don't care what the result of `range(3)` is, we just want to go through `range(3)` – Adam Smith Jan 28 '14 at 20:53
  • 2
    It does store it, but it makes it clear to future "archaeologists" that you don't care what it is. – mhlester Jan 28 '14 at 20:54
  • you could do `for _ in lst: print _` and it will work as intended, but your colleagues will look at you funny because you've explicitly said "Hey iterate through `lst` but we won't use each element -- OH WAIT LET'S USE THAT ELEMENT ANYWAY" – Adam Smith Jan 28 '14 at 20:54