About Python variables and objects

■ About variables

In a programming language, a variable is an area that stores some value. For Python, you don't need to declare variables before using them. When you assign a value to a variable, the area is ready. In an object-oriented language like Python, it's best to think of a variable as not storing the value itself, but rather a "reference" that points to the value of the variable.

>>> name1 = "Ichiro Yamada"

◎ Figure n1 n1.png

Alternatively, the "variable name" can be thought of as a tag-like image set in the value.

◎ Figure n2 n2.png

If you assign a variable to another variable, it will point to the same value, as follows:

>>> name1 = "Ichiro Yamada"
>>> name2 = name1

◎ Figure n3 n3.png

■ Check the ID of an object with the id () function

In Python, all values, including numbers and strings, are objects. Use the id () function to find out the ID (identification value) of an object. When the id () function is executed with the variable name as an argument, the ID of the referenced object is displayed. If you look up the IDs of variables name1 and name2 with the id () function in the above example, you can see that they refer to objects with the same ID.

>>> name1 = "Ichiro Yamada"
>>> name2 = name1
>>> id(name1)
4339005200 ← Same ID
>>> id(name2)
4339005200 ← Same ID

■ When reassigning a value to a variable

What if you reassign a different value to a variable? In the following example, first, 10 is assigned to the variable num in ①, "1" is added to the value of the variable num in ②, and it is assigned to the variable num.

>>> num = 10	←①
>>> num = num + 1	←②

In this case, a new object with the value "11" is created in ②, and its reference is stored in the variable num. In other words, in ① and ②, the variable num points to a different object. This can be confirmed using the id () function.

>>> num = 10
>>> id(num)
4297538176
>>> num = num + 1
>>> id(num)
4297538208 ← ID changed (reference changed)

■ Mutable and immutable values

Python data types are broadly divided into "mutable" types whose values can be changed later and "immutable" types which cannot be changed.

Mutable list, dictionary, set, .... Immutable strings, numbers, tuples, ...

In Python, basic data types such as strings and numbers are also immutable, that is, types that cannot be changed later. By the way, in the above example, 1 was added to the value of the variable num and reassigned to the variable num.

>>> num = 10		←①
>>> num = num + 1	←②

At first glance, this seems to change the value of the variable num, so isn't the numeric type a mutable type? You might think, but it's not. As you can see from the execution result of the id () function, the variable num points to a different value in ① and ②.

■ Lists are mutable, tuples are immutable

Now, in Python, a "list" is a mutable, a type whose value can be changed later. The following example generates a list "ages" with three integers as elements and modifies the third element.

>>> ages = [1, 2, 3]
>>> ages[2] = 4
>>> ages
[1, 2, 4]

Looking at the id () function, it goes without saying that the ID has not changed even after changing the value of the element.

>>> ages = [1, 2, 3]
>>> id(ages)
4338960072
>>> ages[2] = 4
>>> id(ages)
4338960072 ← ID is the same

Tuples, on the other hand, are immutable types. Attempting to change the value of an element will result in an error.

>>> nums = (1, 2, 3)
>>> nums[0] = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

■ Character strings are also immutable

The string is also an immutable type. Therefore, if you try to change the internal characters as follows, you will get an error.

>>> str = "abc"
>>> str[1] = "d" #The second letter is ""d"Substitute
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

As an example that is easily misunderstood, let's look at the following example.

>>> str = "abc"
>>> str = str + "bcd" #str and"bcd"Concatenated and reassigned to str ← ①
>>> str
'abcbcd'

In this example, since the variable str and the character string "" bcd "" are concatenated in ①, it looks like the character string has been changed, but that is not the case. In ①, a new character string "" abcbcd "" is generated, and its reference is stored in the variable str. If you check with the id () function, you can see that the ID has been changed after ①.

>>> str = "abc"
>>> id(str)
4301952704
>>> str = str + "bcd"
>>> id(str)
4339056968 ← ID changed
>>> str
'abcbcd'

Recommended Posts

About Python variables and objects
About Python, len () and randint ()
About Python datetime and timezone
Python class variables and instance variables
Python variables and object IDs
About Python and regular expressions
About Python and os operations
Python # About reference and copy
About Python sort () and reverse ()
Getting Started with python3 # 2 Learn about types and variables
[Python] Variables
About _ and __
About installing Pwntools and Python2 series
perl objects and python class part 2.
About python dict and sorted functions
About dtypes in Python and Cython
Assignments and changes in Python objects
About Python pickle (cPickle) and marshal
[Python] About Executor and Future classes
About Python, from and import, as
perl objects and python class part 1.
About python slices
About python comprehension
[Python] Use and and or when creating variables
About Python tqdm.
About python yield
About python, class
About python inheritance
About python, range ()
About python decorators
A story about Python pop and append
About python reference
About Python decorators
[Python] About multi-process
Talking about old and new Python classes
Talking about Python class attributes and metaclasses
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
Python variables and data types learned in chemoinformatics
[python] Difference between variables and self. Variables in class
A story about Go's global variables and scope
Think about depth-priority and width-priority searches in Python
About the difference between "==" and "is" in python
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Python] Chapter 02-01 Basics of Python programs (operations and variables)
Practice applying functions and global variables in Python
Trouble with Python pseudo-private variables and class inheritance
A story about modifying Python and adding functions
[Python] Learn about asynchronous programming and event loops
About the * (asterisk) argument of python (and itertools.starmap)
About shallow and deep copies of Python / Ruby
[python] Compress and decompress
About Class and Instance
Python memorandum numbering variables
[Python] Get environment variables
About function arguments (python)
Global and local variables 2
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
[Python] Memo about functions