Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Use id () to understand how the six key concepts in Python are.

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to use id () to understand the six key concepts in Python. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

More than 70 built-in functions are available when you start any Python interpreter. Every Python learner should not be unfamiliar with some ordinary learners. For example, we can use len () to get the length of an object, such as the number of items in a list or dictionary. To give another example, we can use print () to print out the objects of interest for learning and debugging.

In addition, almost all Python programmers should see the use of the built-in id () function in the tutorials to guide specific Python concepts. However, as far as I know, this information is scattered. In this article, I want to systematically review the use of the id () function to understand six key Python concepts.

1. Everything is an object in Python

As a popular object-oriented programming language, Python uses objects everywhere in its implementation. For example, built-in data types such as integers, floating-point numbers, strings, lists, and dictionaries are objects. Moreover, functions, classes, and even modules are also used as objects.

By definition, the id () function takes an object and returns its identity, the memory address expressed as an integer. Therefore, we can use this function to prove that all objects in Python are real.

> import sys > class Foo:... Pass... > > def foo ():... Pass. > > a_tuple = ('Error', 404) > a_dict = {' error_code': 404} > a_list = [1,2,3] > a_set = set ([2,3,5]) > objects = [2,2.2, 'hello', a_tuple, a_dict, a_list, a_set, Foo, foo, sys] > for item in objects:. Print (f'{type (item)} with id: {id (item)}'). With id: 4479354032 with id: 4481286448 with id: 4483233904 with id: 4483061152 with id: 4483236000 with id: 4483236720 with id: 4483128688 with id: 140235151304256 with id: 4483031840 with id: 4480703856

In the code snippet above, you can see that each item in the object list can be used in the id () function, which displays the memory address of each object.

What I think is interesting is that, as the function itself, the id () function should also have its memory address.

> print (f'{type (id)} with id: {id (id)}') with id: 4480774224

two。 Variable assignments and aliases

When creating variables in Python, you typically use the following syntax:

Var_name = the_object

This process basically binds an object created in memory to a specific variable name. What happens if you assign another variable to a variable, such as var_name1 = var_name?

Consider the following example. In the following code snippet, we first create a variable named hello and assign it a string value. Next, we create another variable named world by assigning the previous variable hello. When we print out their memory addresses, we find that hello and world both have the same memory address, indicating that they are the same object in memory.

> hello = 'Hello wordings' > print (f'{hello} from: {id (hello)}') Hello World! From: 4341735856 > world = hello > print (f'{world} from: {id (world)}') Hello World! From: 4341735856 > bored = {'bored: 0,' baked: 1}} > print (f'{bored} from: {id (bored)}') {'aqu: 0,' baked: 1} from: 4341577200 > more_bored = bored > print (f'{more_bored} from: {id (more_bored)}') {'aqu: 0,' baked: 1} from: 4341577200 > more_bored ['c'] = 2 > > bored {'axiang: 0,' baked: 1 More_bored {'averse: 0,' baked: 1, 'catered: 2}

In this case, the variable world is often called an alias for the variable hello, and the process of creating a new variable by assigning an existing variable can be called an alias. In other programming languages, aliases are very similar to pointers or references related to underlying objects in memory.

In the above code, we can also see that when we create an alias for the dictionary and modify the alias data, the change will also be applied to the original variable, because in the background, we modified the same dictionary object in memory.

3. Comparison operator: = = vs. Is

In various cases, we need to compare two objects as decision points in order to apply different functions when specific conditions are met or not met. In terms of equality comparison, we can use two comparison operators: = = and is. Some new Python learners may mistakenly think that they are the same, but there are nuances.

Consider the following example. We created two lists of the same items. When we compare two lists using the = = operator, the result is True. When we compare two lists using the is operator, the result is False. Why do they produce different results? This is because the = = operator compares values, while the is operator compares identities (that is, memory addresses).

As you might expect, these variables refer to the same object in memory, and they not only have the same value, but also have the same identity. This results in the same evaluation results for the = = and is operators, as shown in the following example involving str0 and str1:

> list0 = [1,2,3,4] > list1 = [1,2,3] 4] > print (f'list0 = = list1: {list0 = = list1}') list0 = = list1: True > print (f'list0 is list1: {list0 is list1}') list0 is list1: False > print (f'list0 id: {id (list0)}') list0 id: 4341753408 > > print (f'list1 id: {id (list1)}') list1 id: 4341884240 > str0 = 'Hello' > > str1 = str0 > print (f'str0 = = str1: {str0 = = str1}') str0 = str1: True > print (f'str0 is str1: {str0 is str1}') str0 is str1: True > print (f'str0 id: {id (str0)}') str0 id: 4341981808 > print (f'str1 id: {id (str1)}') str1 id: 4341981808

4. Integer cache

One set of data that we often use in programming is integers. In Python, the interpreter usually caches small integers between-5 and 256. This means that when you start the Python interpreter, these integers will be created and available for later use in memory. The following code snippet shows this feature:

> number_range = range (- 10265) > id_counters = {x: 0 for x in number_range} > id_records = {x: 0 for x in number_range} > for _ in range (1000):. For number in number_range:... Idid_number = id (number)... If id_ records [number]! = id_number:... Id_ records = id_number. Id_ countermeasures [number] + = 1... > > [x for x in id_counters.keys () if id_ countermeasures [x] > 1] [- 10,-9,-8,-7,-6, 257, 258, 259, 260, 261,262,263,264]

In the above code, I created two dictionaries, where id_counters tracks the count of the unique identity of each integer, and id_records tracks the latest identity of the integer. For integers between-10 and 265, if the identity of the new integer is different from the existing integer, the corresponding counter is incremented by 1. I repeated this process 1000 times.

The last line of code uses the list derivation technique to show you integers with multiple identities. Obviously, after 1000 times, integers from-5 to 256 have only one identity for each integer, as described in the previous paragraph. To learn more about understanding the Python list, you can refer to my previous article on this:

5. Shallow and deep copy

Sometimes we need to make a copy of an existing object so that we can change one copy without changing another. The built-in replication module provides two ways to do this: copy () and deepcopy (), which make shallow and deep copies, respectively. If you don't know what they are, let's use the id () function to understand these two concepts.

> > import copy > original = [[0,1], 2,3] > print (f'{original} id: {id (original)}, embeded list id: {id (original [0])}') [[0,1], 2,3] id: 4342107584, embeded list id: 4342106784 > > copycopy0 = copy.copy (original) > print (f'{copy0} id: {id (copy0)}, embeded list id: {id (copy0 [0])}') [[0,1], 2,3] id: 4341939968 Embeded list id: 4342106784 > copycopy1 = copy.deepcopy (original) > print (f'{copy1} id: {id (copy1)}, embeded list id: {id (copy1 [0])}') [[0,1], 2,3] id: 4341948160, embeded list id: 4342107664

We first created a list variable named original, which consists of a nested list and two integers. Then we made two copies (copy0 and copy1) using the copy () and deepcopy () methods, respectively. As we expected, the original copy0 and copy1 have the same value (that is, [0Magne1], 2p3]). However, they have different identities because, unlike aliases, both the copy () and deepcopy () methods create new objects in memory, giving the new copy a different identity.

The most essential difference between a shallow copy and a deep copy is that a deep copy recursively creates a copy of the original compound object, while a shallow copy retains references to existing objects where applicable. In the example shown above, the variable original is actually a composite object (that is, one list is nested within another).

In this case, using the copy () method, the first element of the variable copy0 has the same identity (that is, the same object) as the original first element. By contrast, the deepcopy () method copies the nested list in memory so that the first element in the copy1 has a different identity from the original element.

But what does "recursion" mean in deep replication? This means that if there are multiple layers of nesting (for example, a list nested in a list and another list), the deepcopy () method creates a new object for each layer. See the following example to learn about this feature:

> > mul_nested = [0,1], 2], 3] > print (f'{mul_nested} id: {id (mul_nested)}, inner id: {id (mul_nested [0])}, innermost id: {id (mul_nested [0] [0])}') [0,1], 2], 3] id: 4342107824, inner id: 4342106944 Innermost id: 4342107424 > > mul_nested_dc = copy.deepcopy (mul_nested) > print (f'{mul_nested_dc} id: {id (mul_nested_dc)}, inner id: {id (mul_nested_dc [0])}, innermost id: {id (mul_nested_dc [0] [0])}') [0,1], 2], 3] id: 4342107264, inner id: 4342107984, innermost id: 4342107904

6. Data variability

An advanced topic in Python programming is related to data variability. In general, immutable data refers to objects whose values cannot be changed after creation, such as integers, strings, and tuples. By contrast, mutable data refers to objects whose values can be changed after creation, such as lists, dictionaries, and collections.

One thing to note is that by "changing the value", we mean whether the underlying object in memory can be changed. A detailed discussion of data variability can be found in my last article:

Immutable and changeable

For the purpose of this article discussing the id () function, let's consider the following example. For immutable data types (the integer variable thousand in the code snippet), when we try to change its value, a new integer is created in memory, as reflected by the new identity of the thousand variable. In other words, the original underlying integer object cannot be changed. Trying to change an integer will only create a new object in memory.

> > thousand = 1000 > print (f'{thousand} id: {id (thousand)}') 1000 id: 4342004944 > > thousand + = 1 > print (f'{thousand} id: {id (thousand)}') 1001 id: 4342004912 > > numbers = [4,3,2] > > print (f'{numbers} id: {id (numbers)}') [4,3,2] id: 4342124624 > > numbers + = [1] > > print (f'{numbers} id: {id (numbers)}') [4,3,2,1] id: 4342124624

If this puzzles you, let's take a look at what happens to the variable data type-in our case, the list variable number. As shown in the code above, when we try to change the value of a number, the variable sign is updated, and the updated list still has the same identity, confirming the variability of list-type objects.

This is how the editor shares the use of id () to understand the six key concepts in Python. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report