1

To my knowledge, list.append(item) in Python adds an item to the end of the existing list.

Now, considering the following program:

numlist=[1,2,3]
vallist = ["a","b","c"]
db = []
card = ["number","value"]
for i in range(len(numlist)):
    card[0]=numlist[i]
    card[1]=vallist[i]
    db.append(card)
print(db)

I was expected the output [[1, 'a'],[2, 'b'],[3, 'c']],

But, to my surprise, the output came as: [[3, 'c'], [3, 'c'], [3, 'c']]

I have tried, visualizing the aforementioned program using Python Tutor: Python Tutor Output

But I don't understand, why all 3 indices of the list indicate the last input of the list. What am I missing here? Also, how can I get my desired output using the list append method?

Thank you.

Amlan Saha Kundu
  • 186
  • 1
  • 10
  • Short answer: `append` doesn't make copies, it just inserts an alias. You keep appending the *same* `list` over and over, then mutating the `list` in place, but since you inserted nothing but aliases to the same `list`, all aliases show the effects of the final mutation. – ShadowRanger Dec 26 '21 at 14:56
  • Obligatory reading: https://nedbatchelder.com/text/names.html – chepner Dec 26 '21 at 15:00
  • @ShadowRanger How can I resolve this issue? – Amlan Saha Kundu Dec 26 '21 at 15:08
  • @AmlanSahaKundu: Read the duplicate's answers. Many solutions. Short version is: Don't use the exact same `list` over and over, or copy it on `append`. – ShadowRanger Dec 26 '21 at 17:19

0 Answers0