Python__ a reference to a list take the Append action as an example

Source: Internet
Author: User

For a mutable type such as a list, it does not change the memory address for its operation.

If the element stored in the list is an immutable type such as an integer, the address will change if the element is modified, such as:

>>> a = [1,2,3]>>> b =1  Plus to B list > >> b.append (a[0])>>> a[123] >>> b[1]

This time change the value of the first element of the A list:

>>> a[00>>> a[023]>>> b[1]

As you can see, B is unaffected because the element type is an immutable type (integer)

But if the element type is a mutable type, such as a list:

>>> a[0] = [0,0,0]>>> b.append (a[0]) #把a [ 0 ] Inside this list element join B list inside >>> a[[00023 ]>>> b[1, [000]]

Now if you change the first list element of the A list, such as adding a value with append:

 >>> a[0 ].append ( " ha   " )  > >> b[ 1 , [ 0 , 0 , 0 ,  " ha   '  

Summary: For nested mutable types, if another variable is added by reference, it is also the same memory address, and modifying one still affects the other.

Python__ a reference to a list take the Append action as an example

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.