1
list= []

x = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

for i in range(2):

          list.append(x)

list[0][0]="x"

print list

And after printing I get this:

[['x', 'B', 'C', 'D', 'E', 'F', 'G'], ['x', 'B', 'C', 'D', 'E', 'F', 'G']]

The first item in every list was replaced by 'x' whereas I only wanted the first item in the first list to be replaced by 'x'(hence the line list[0][0]="x")

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
95xxxtent
  • 21
  • 3

1 Answers1

1

The line list.append(x) adds a reference to x into list. Both sublists end up pointing to the same object (as does x). In fact, doing x[0] = 'x' would have the exact same effect as list[0][0] = 'x'. To make the sub-lists independent, make a copy by doing list.append(x.copy()) or list.append(x[:])

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264