Some understanding of Python variables

Variables in Python are objects, abstracting addresses and memory. Variables can be understood as "pointers". Variables store the address of the value, not the variable itself.

For example: a = 2

 

The variable a actually stores the address of 2 in memory, not the value of 2.

With this understanding we look at some procedures:

 

1. It's easy to understand, a = 2, b = a, b is naturally equal to 2

2. a = 3, output 3, 2 is also easy to understand

3. According to the serial number 1 and serial number 2 to understand the output as [2], [2] is no problem

4. The output of serial number 4 is [3], [3] according to serial number 1 and serial number 2 to understand that what should be output here is [3], [2] right?

5. If you understand it according to serial number 4, the output here should be [4], [4], why did it become [4], [3] again?

The reason for the above results involves immutable data types and variable data types in Python

Immutable data types: integer int, float, string, and tuple

Variable data types: list list and dictionary dict

The essence of both depends on whether the data in memory is modified

Because a is an immutable data type, reallocate space when assigning a new value, and store the value to the new memory address to variable a. The original value 2 has not been changed, so the value 2 in the address saved in the b variable No change.

This can explain why the output of serial number 2 is 3, 2

 Because a is a list, it is a variable data type, so the address of a has not changed. a [0] only changes the immutable data type saved in the list.

This can explain the output of serial number 3, because a and b save the list address 47349576, the content of this list changes, and the output of both a and b will change.

a = [4] means that the first address of the list saved by a is overwritten by the first address of list [4], and b is still the first address of the original list saved, that is, 47349576, so the output of sequence number 5 is not [4], [4].

 note:

 The list address of a = [3] and b = [3] are different, the same is only the address of immutable data type 3

 

Guess you like

Origin www.cnblogs.com/Mydream6/p/12761349.html