Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why i can't get the result of appending list in python

d={}
for i in range (5):
    d['key']=i
    lst.append(d)
print(lst) 
>>>[{'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}]

Why i didn’t got this result plz :>>>[{'key': 0}, {'key': 1}, {'key': 2}, {'key': 3}, {'key': 4}] ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This code will work:

lst = []
for i in range(1, 6):
    lst.append({"key", i})
print(lst)

The problem was that you are appending the variable d to lst. the value of lst is now [d, d, d, d, d]. When printing, this evaluates to d‘s current value, which happens to be {'key', 4}. My code appends the value of d to the list without creating d. This is at least my interpretation of this. Could be wrong.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading