About Python, the problem of data being overwritten after looping using list.append ()

Source: Internet
Author: User

In a reptile combat, you need to add the dictionary to the list, the unexpected situation appeared!!! The following is a brief analysis of the situation:

1List = []2DIC = {}3  forIinchRange (5):4dic['Num'] =I5 list.append (DIC)6     Print(ID (DIC))7 Print(list)81366520969136652096Ten136652096 One136652096 A136652096 -[{'Num': 4}, {'Num': 4}, {'Num': 4}, {'Num': 4}, {'Num': 4}]

The results were unexpected, not what we thought was simple.

[{' num ': 0}, {' num ': 1}, {' num ': 2}, {' num ': 3}, {' num ': 4}]

In my own understanding is:

For example, every DIC gives a list a position, but your dic is outside the loop, and you say that each loop you give is an address, the value of DIC changes, the new loop value will overwrite the value of the previous loop, and the value of the list is changed.

Correct practice:

1List = []2  forIinchRange (5):3DIC = {}4dic['Num'] =I5 list.append (DIC)6     Print(ID (DIC))7 Print(list)81383838889136652192Ten138383408 One138384272 A138383792 -[{'Num': 0}, {'Num': 1}, {'Num': 2}, {'Num': 3}, {'Num': 4}]

The correct approach is to put DIC in the loop so that each cycle will be a new DIC, assigning a different address.

About Python, using list.append () after a loop, the data is overwritten

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.