Consider the following Python code, if the run ends, what is the result of the run on the command line?

Source: Internet
Author: User
Tags shallow copy

1 1. L = []2 for in xrange:3 3.     L.append ({' num ': i})4print l
1 1. L = []2 2. A = {' num ': 0}3 for in Xrange ():4 4.     a[' num '] = i5 5.     L.append (a)6print l

Are the two sections of code running the same, if not the same, what are the reasons?

The result of the above code:

1 1. [{' num ': 0},{' num ': 1},{' num ': 2},{' num ': 3},{' num ': 4},{' num ': 5},{' num ': 6},{' num ': 7},{' num ': 8},2 {' num ': 9}]

The result of the code below:

1 1. [{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},2 {' num ': 9}]

So here's the reason:

The reason is that the dictionary is a mutable object, and in the operation of L.append (a) below, the reference to dictionary A is passed to the list L, when
Continue to modify the value of a[' num '), the value in L will also change, equivalent to a shallow copy.

Consider the following Python code, if the run ends, what is the result of the run on the command line?

Related Article

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.