0

I'm trying to create a new list by changing the other in for loop, using append method. But I a have a trouble with it.

My simple code:

l1=[]
l2=[0,0]
for i in range(4):
    l2[0]+=1
    l1.append(l2)
    print l2
print l1

Return:

[1, 0]
[2, 0]
[3, 0]
[4, 0]
[[4, 0], [4, 0], [4, 0], [4, 0]]

But I expected that list l1 would be like this: [[1,0], [2,0], [3,0], [4,0]] Where I made a mistake?

Ilya
  • 9
  • 1

2 Answers2

1

You need to append a copy of the list and not a reference to it.

l1.append(l2[:])

Test Run:

>>> l1 = []
>>> l2 = [0, 0]
>>> for i in range(4):
        l2[0] += 1
        l1.append(l2[:])
        print l2


[1, 0]
[2, 0]
[3, 0]
[4, 0]
>>> l1
[[1, 0], [2, 0], [3, 0], [4, 0]]
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
1

You are appending a reference to the list. And since, at the end of the loop, the value of l2 is [4,0], each list inside l1 is [4,0]

You can just append a copy of the list with the help of the list() built-in method or, using the slicing notation as shown below

l1=[]
l2=[0,0]
for i in range(4):
    l2[0]+=1
    l1.append(list(l2)) # or l1.append(l2[:])
    print l2
print l1

If you are not able understand the idea, you can use the viz mode of codeskulptor and run the code line by line, understand it properly.

anirudh
  • 4,116
  • 2
  • 20
  • 35