Skip to content

Types of objects in Python | with examples

  • by

Python is an Object-oriented programing language so everything in Python is an object. There are two types of objects in python i.e. Mutable and Immutable objects.

The difference between both types of objects is Simple, a mutable object can be changed after it is created, and an immutable object can’t.

Types of objects in Python

Understand with example.

Immutable Objects

The immutable object can’t be changed after it is created Objects of built-in types like (int, float, bool, str, tuple, Unicode) are immutable.

These are quicker to access and are expensive to change because it involves the creation of a copy.

Check whether tuples are immutable or not?

tuple1 = (1, 2, 3)
tuple1[0] = 4
print(tuple1)

Output: TypeError: ‘tuple’ object does not support item assignment

Check strings are immutable

msg = "Hello"
msg[0] = 'Bye'
print(msg)

Output:

Types of objects in Python

Mutable Objects :

Custom classes are generally mutable for example list, dict, and set. The use of mutable objects is recommended when there is a need to change.

Let’s see if lists are mutable or not?

al = ["A", "B", "C"]
print(al)

al[0] = "D"
al[-1] = "E"
print(al)

Output:

[‘A’, ‘B’, ‘C’]
[‘D’, ‘B’, ‘E’]

Do comment if you have any doubts or suggestions on this Python object tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading