Object in Python

Overview

In Python, everything is an object. This includes not only complex data structures but also basic data types such as integers, strings, and lists. Understanding the nature of objects in Python is crucial because it affects how data is manipulated and passed around in your programs. Objects in Python can be categorized as either mutable or immutable, which influences their behavior, especially when they are used as function arguments.

Mutable vs. Immutable Objects

  • Mutable Objects: These are objects whose state or content can be changed after they are created. Examples include lists, dictionaries, and sets. When mutable objects are passed as arguments to a function, any modifications made to the object within the function will reflect in the original object outside the function. This is because the function parameter becomes a new reference to the same object.

  • Immutable Objects: These are objects whose state or content cannot be changed once they are created. Examples include integers, strings, and tuples. When immutable objects are passed as arguments to a function, any changes made within the function do not affect the original object.

Example

Consider the following example to illustrate how objects behave when passed as function arguments:

def f(n, list1, list2):
   list1.append(3)  #A
   list2 = [4, 5, 6]  #B
   n = n + 1
 
x = 5
y = [1, 2]
z = [4, 5]
f(x, y, z)
x, y, z
 
(5, [1, 2, 3], [4, 5])
#A One item added to list1.
#B list2 is replaced locally with a new list.

Explanation

  • Line #A: The function f appends the integer 3 to list1. Since list1 is a mutable object, the change is reflected in the original list y outside the function. Thus, y becomes [1, 2, 3].

  • Line #B: The function assigns a new list [4, 5, 6] to list2. However, this change is local to the function f and does not affect the original list z outside the function. This is because list2 is reassigned to a new list object, and the reference to the original list z is lost within the function scope.

  • The integer n is incremented by 1 within the function, but since integers are immutable, this change does not affect the original value of x outside the function. Thus, x remains 5.

Understanding these concepts is fundamental to effectively managing data and avoiding unintended side effects in your Python programs.