Differences between Python reference types and value types

Source: Internet
Author: User

Differences between Python reference types and value types

Python data types are divided into value type and reference type. The differences are as follows:

Value Type:

The object itself cannot be modified. The modification of the value actually directs the variable to a new object.
Contains: strings, tuples, and values, which cannot be modified.

Reference Type:

The object itself can be modified,
Including: List and dictionary, which can be modified

Example:

a = 11 print id(a) a = 16 print id(a)

Result:

43525053L57628312L

Modify the value of the value type to point it to a new memory address without changing the value of variable B.

l = [1,2,3] print id(l) l[0] = 0 print id(l)

Result:

19775281L19775281L

Modify the value of the reference type because the address of listb is the same as that of lista.

Generally, you can use the sharding operation only to copy the value.

listb = lista[:]

Next, let's take a look at the value type and reference type of python separately.

Value Type:

Contains: strings, tuples, and values, which cannot be modified.

Reference Type:

Including: List and dictionary, which can be modified

a = 2b = aa = 3

Modify the value of the value type to point it to a new memory address without changing the value of variable B.

lista = [1,2]listb = listalista[0] = 3

Modify the value of the reference type because the address of listb is the same as that of lista.

Generally, you can use the sharding operation only to copy the value.

listb = lista[:]

Summary

The above section describes the differences and usage of Python reference types and value types. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.