-3

Why does input() not return a constant id for strings?

>>> id(input())
String
2339026478168
>>> id(input())
String
2339026478224

This is compared to creating 2 strings of the same value:

>>> id('String')
2339026468680
>>> id('String')
2339026468680

This directly impacts the is operator

Djones4822
  • 577
  • 3
  • 6
  • 23

1 Answers1

-1

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

Source: https://docs.python.org/3.7/library/functions.html#id

There are situations that some values have the same id, because they are implemented as singletons. These are usually values that are statistically going to occur often in a typical program. Some obvious examples of this are None, True, and False.

>>> variable = True
>>> variable is True
True

Some non-obvious examples of this are relatively small numbers.

>>> variable = 256
>>> variable is 256
True
>>> variable = 257
>>> variable is 257
False

This is also why people advise using the == operator over is for value comparison.

ProfOak
  • 541
  • 4
  • 10
  • My question was more regarding why input() doesn't construct the id the same way every time. – Djones4822 Jul 27 '18 at 03:42
  • @Apc0243 Input doesn't "construct" the id. If you have carefully read the answer you will know it. – Mia Jul 27 '18 at 03:56
  • 1
    I don't have a great understanding of all the Python internals, but I'll hazard to guess anyways. It might be because a literal variable assignment, ie `var = 'string'`, gives the same id and `input()` doesn't because the former is a constant/literal string and input can be anything. This is just speculation, so please take it with a grain of salt – ProfOak Jul 27 '18 at 04:06
  • @pkqxdd my question was less to do with how `id()` is executed, and more why a string of equal value is associated with the same id while the same string from input() is not. My best guess is that on creation of a string value the memory address is established and checked each time while input() has no ability to reference that address? So every time input() produces a new object, regardless of its value, while strings created of the same value through more traditional pythonic means don't have this issue? I apologize if this is obvious, I just don't really understand – Djones4822 Jul 28 '18 at 03:08