1

I'm creating a list of lists of lists. When I choose a specific index, it sets several list entries simultaneously. What's going on here?

x = []
for i in range(3,6+1,1):
    x.append([['','']] * i)

x[0][0][0] = 1
for col in x:
    print col

output:

[[1, ''], [1, ''], [1, '']]
[['', ''], ['', ''], ['', ''], ['', '']]
[['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
[['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]

It's still an open question as to why that doesn't work... Here's a solution, though...

x = []
for i in range(3,6+1,1):
    y = ['','']
    tmp = []
    for j in range(i):
        tmp.append(y[:])
    x.append(tmp)

x[0][0][0] = 1
for col in x:
    print col

output:

[[1, ''], ['', ''], ['', '']]
[['', ''], ['', ''], ['', ''], ['', '']]
[['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
[['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
nick_name
  • 1,353
  • 3
  • 24
  • 39

1 Answers1

3

When you multiply the list, objects are re-used, so when you modify one of them, you appear to modify "all" of them. In fact, there is only one inner list, but it appears in multiple places in the outer list!

>>> x = []
>>> x.append([['','']] * 3)
>>> x
[[['', ''], ['', ''], ['', '']]]
>>> x[0][0][0] = 1
>>> x
[[[1, ''], [1, ''], [1, '']]]

If the inner lists are created separately, so that they are distinct objects, you don't get this problem:

>>> x = [[]]
>>> x[0].append(['',''])
>>> x[0].append(['',''])
>>> x[0].append(['',''])
>>> x
[[['', ''], ['', ''], ['', '']]]
>>> x[0][0][0] = 1
>>> x
[[[1, ''], ['', ''], ['', '']]]

If you create the list using a comprehension, you also avoid the problem, for example:

x = [[['',''] for _ in range(3)]]
DNA
  • 42,007
  • 12
  • 107
  • 146