Python 3: Object, ID, Type

By Xah Lee. Date:

Every object has a id.

# -*- coding: utf-8 -*-
# python 3

# every object has a id.
                                # sample id values
print(id(3))                    # 137396032
print(id(4))                    # 137396048
print(id("3"))                  # 3070494944
print(id(""))                   # 3070685728

Every object has a type.

# -*- coding: utf-8 -*-
# python 3

# 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'>
# -*- coding: utf-8 -*-
# python 3

# Two different objects will have different id. “is” operator can be used to test

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

Every object has a value. (here, the value means python's internal value, not what you see when you call print().)

# -*- coding: utf-8 -*-
# python 3

print(id([3, 4]))      # 3069953132   (note: id may not be the same for you)
print(id([3, 7]))      # 3069953132
# from the output, you can see that [3, 4] and [3, 7] were the same object, yet the value changed

# all python object has value.
# here, “value” doesn't mean a variable's value, but internal value of python object

# 3 is a object
print(3)

# The value of the object 3 represents the math idea 3, in python's guts.
# The value of the object 3 cannot be changed.

# array is a object
print([3, 4])          # [3, 4]
# it's values is a container to 2 other python objects, 3 and 4

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

Example of mutable object: list.

Example of immutable object: string, tuple.

# -*- coding: utf-8 -*-
# python 3

# 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]

If you have a question, put $5 at patreon and message me.