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.
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[:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With