Pass by value & pass by reference

 Pass by value & pass by reference

In Python, the concept of "pass by value" and "pass by reference" can be a bit misleading because it's actually a combination of both, depending on the data type being passed.


1. Passing by Value (Immutable Objects):

   - Immutable objects, such as numbers, strings, and tuples, are passed by value in Python.

   - When you pass an immutable object to a function, a copy of the object is created, and the function receives this copy.

   - Changes made to the parameter inside the function do not affect the original object.


   Example:


   ```python

   def modify_value(val):

       val = 10  # Changes the local copy of 'val'


   a = 5

   modify_value(a)

   print(a)  # Output: 5 (unchanged)

   ```


2. Passing by Reference (Mutable Objects):

   - Mutable objects, such as lists and dictionaries, are passed by reference in Python.

   - When you pass a mutable object to a function, the function receives a reference to the original object, not a copy.

   - Changes made to the parameter inside the function affect the original object.


   Example:


   ```python

   def modify_list(my_list):

       my_list.append(4)  # Modifies the original list


   my_list = [1, 2, 3]

   modify_list(my_list)

   print(my_list)  # Output: [1, 2, 3, 4] (original list is modified)

   ```


In summary, the "pass by value" and "pass by reference" behavior in Python can be understood as follows:


- Immutable objects (integers, strings, tuples) are passed by value. Changes inside the function don't affect the original object.

- Mutable objects (lists, dictionaries) are passed by reference. Changes inside the function affect the original object.


Understanding this distinction is important for writing efficient and predictable code in Python, especially when dealing with functions and data manipulation.


Comments

Popular posts from this blog

Programming in Python