-1

When I enter t=[[False]*2]*2, I get the list [[False, False], [False, False]]. But when I enter t[0][0] = True, t[1][0] also changes to True, leaving me with [[True, False], [True, False]]. I only want [[True, False], [False, False]]. As a second option, I could assign t=[[False]*2, [False]*2] and then changing t[0][0] = True gets me what I want ([[True, False], [False, False]]), but my real list is a lot bigger than that, so I would rather not use option 2. I figured that this was a similar issue to cloning versus copying with lists, so I tried: ([[False]*2])*2

([False]*2)*2

[[False]*2][:]*2

t = [False]*2 t = t*2

list([False]*2)*2

list([[False]*2])*2

[list([False]*2)]*2. None of these worked. Is there any way to do this without importing any package?

Prayag Gordy
  • 667
  • 7
  • 18

1 Answers1

0

If you build your lists using list comprehension, each list object will point to a unique address, rather than share the same reference.

t = [[False for x in range(2)] for y in range(2)]
t[0][0] = True
t  # [[True, False], [False, False]]
Jordan Bonitatis
  • 1,527
  • 14
  • 12
  • Of course! I used list comprehension everywhere else but I forgot to use it here. By the way, `xrange` does not work in Python 3 (it's just `range`.) Is there really no way to do this without list comprehension though? – Prayag Gordy Mar 04 '17 at 22:01
  • @P.Gordy There's also `itertools.repeat(val, numberoftimes)`, however the list comprehension will be faster. And if you nest the `repeat` then it's getting ugly really fast. – MSeifert Mar 04 '17 at 22:05
  • 1
    The `[False for x in range(2)]` can actually just be `[False]*2`. Only the second one needs to have the `for y in range(2)`. – Prayag Gordy Mar 04 '17 at 22:09