Python: Object, ID, Type

By Xah Lee. Date: . Last updated: .

Object ID

Every object has a id. it's a unique number of current session, based on memory address.

# sample id values
print(id(3))     # 137396032
print(id(4))     # 137396048
print(id("3"))   # 3070494944
print(id(""))    # 3070685728

Object type

Every object has a type.

print(type(4))   # <class 'int'>
print(type(4.2)) # <class 'float'>
print(type("3")) # <class 'str'>
print(type( [3, 4, 5] ))   # <class 'list'>
print(type( (3, 4, 5) ))   # <class 'tuple'>

print(type(type(4)))  # <class 'type'>

Testing if objects are identical

is operator tests if two objects have the same ID.

print(3 is 4)    # False
print(3 is 3)    # True
print("7" is "7")     # True

Mutable vs immutable objects

Object are said to be “mutable” or “immutable”.

# mutable objects (For example, lists, dictionary) may have the same value, but are not same object
print([3, 4] is [3, 4])
# False


aa = [3, 4]
bb = [3, 4]
print(aa is bb)
# False
# here, aa and bb are same object.
aa = [3, 4]
bb = aa
print(aa is bb)  # True

# changing aa also change bb, because they are same object
aa[0] = "x"
print(bb)  # ['x', 4]