Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a list to an empty python list issue

I am Python beginner with no prior programming experience. I apologize in advance if this question sounds too lame to answer to, but there is something I am confused with. It's related to adding a particular list (l2) to an empty list (l1). What I am trying to do is to increase the value of each of the "l2" elements in each iteration, and then add it to the l2 list.Here is the code:

l1 = []
l2 = [0,1,2,3]

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

print l1

This is the print result that I get:

[1, 2, 3, 4]
[2, 3, 4, 5]
[3, 4, 5, 6]
[[3, 4, 5, 6], [3, 4, 5, 6], [3, 4, 5, 6]]

Why doesn't l2 list look like this:

[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]

? Thank you for the reply.

like image 654
marco Avatar asked Apr 30 '26 03:04

marco


1 Answers

It is because you are appending the same list object each time. You need to copy the list object before you append it, so that you are sure you append a different object.

l1.append(l2[:])
like image 99
icedtrees Avatar answered May 02 '26 15:05

icedtrees