An integer comparison between Python and python

Source: Internet
Author: User

An integer comparison between Python and python

Preface

In Python, everything is an object, and an integer is an object without any exception. You can use = or is to compare objects if they are equal.

= The difference between the is operation is:

  • Is compares whether the IDs of two objects are equal, that is, whether the two objects are the same instance object and whether they point to the same memory address.
  • = Compare whether the content of two objects is equal. By default__eq__()Method.

After knowing the difference between is and =, you may encounter the following confusions, so you have such an article, I tried to hide some obscure things in Python, hoping to help you.

Let's take a look at two sections of code:

Fragment 1:

>>> a = 256>>> b = 256>>> a == bTrue>>>

Fragment 2:

>>> a = 256>>> b = 256>>> a is bTrue>>>

Execute the above two pieces of code in the interactive command line. It is easy to understand that the = B in the code segment returns True, because the values of both objects are 256. For Segment 2, a is B also returns True, which means that a and B point to the same object. You can check whether their id values are equal:

>>> id(a)8213296>>> id(b)8213296>>> 

The results show that they are indeed the same object and point to the same memory address. Is it true that all integer objects are the same instance object as long as their values (content) are equal? In other words, will the is Operation Return True if the integer is equal to or equal to =?

Let's take a look at the following two pieces of code:

Fragment 1:

>>> a = 257>>> b = 257>>> a == bTrue>>>

Fragment 2:

>>> a = 257>>> b = 257>>> a is bFalse>>>

For 257, a is B returns False, and the result may be unexpected. However, we still have to answer the question to find out the truth.

Solution 1

For performance considerations, Python has made a lot of internal optimization work. For integer objects, Python caches frequently used integer objects and saves them to a linked list named small_ints, during the entire lifecycle of Python, no new object needs to be re-created to reference these integer objects, but directly references the objects in the cache. Python places these small integer objects that may be frequently used in the range [-5,256] In small_ints. However, if you need to use small integers, retrieve them from the list, do not create new objects temporarily. Because 257 is no longer in a small Integer Range, although the values of a and B are the same, they exist in Python as two independent objects, independent of each other, and do not interfere with each other.

After figuring out the first problem, we will continue to write a function in the Python interactive command line. Let's look at the following code:

Fragment 1:

>>> c = 257>>> def foo():...  a = 257...  b = 257...  print a is b...  print a is c... >>> foo()TrueFalse

Er, what is the situation? Yes, you are not mistaken. When the values of code a and B in Section 1 are 257, a is B returns True, if a is c returns False and the values of a, B, and c are both 257, why are different results? Does this mean that the newly established cognition is completely rejected? What exactly happened in this code? Is the conclusion in the No. 1 solution incorrect?

Solution 2

A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. the following are blocks: a module, a function body, and a class definition. each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the '-C' option) is a code block. structure-of-a-program

To solve this problem, we need to first understand the concept of program code blocks. A Python program consists of code blocks, which are executed as a minimum basic unit of a program. A module file, a function body, a class, and a single line of code in interactive commands are called a code block. In the code above, it consists of two code blocks. c = 257 serves as a code block, and function foo serves as another code block. To further improve the performance of Python, if an integer object created in a code block has an object with the same value in the code block, it is directly referenced, otherwise, a new object is created. For the sake of performance, Python only creates an object with the same value in an immutable object in the same code block instead of referencing an existing object. Therefore, not only integer objects, but also string objects follow the same principle. Therefore, a is B naturally returns True, while c and a are not in the same code block. Therefore, two objects with 257 values are created in Python. To verify the conclusion, we can use the dis module to look at this code from the bytecode perspective.

>>> import dis>>> dis.dis(foo) 2   0 LOAD_CONST    1 (257)    3 STORE_FAST    0 (a) 3   6 LOAD_CONST    1 (257)    9 STORE_FAST    1 (b) 4   12 LOAD_FAST    0 (a)    15 LOAD_FAST    1 (b)    18 COMPARE_OP    8 (is)    21 PRINT_ITEM       22 PRINT_NEWLINE   5   23 LOAD_FAST    0 (a)    26 LOAD_GLOBAL    0 (c)    29 COMPARE_OP    8 (is)    32 PRINT_ITEM       33 PRINT_NEWLINE      34 LOAD_CONST    0 (None)    37 RETURN_VALUE

We can see that both 257 are obtained from co_consts [1] in the same position of the constant pool.

Summary

After a long article, we come to two conclusions:

1. The small integer object [-5,256] is used repeatedly within the range of the global interpreter and will never be recycled by GC.

2. Immutable objects in the same code block do not create new objects as long as their values are equal. It seems that these knowledge points are not helpful for daily work, because you do not use is to compare the values of Two integer objects. Why should we discuss it? Well, programmers should not give full play to their knowledge.

Well, the above is all the content of this article. I hope this article will help you learn or use python. If you have any questions, please leave a message, thank you for your support.

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.