Sobes.tech
Junior — Middle

How do immutable data types behave when passed to a function as parameters?

sobes.tech AI

Answer from AI

In Python, immutable data types such as strings (str), numbers (int, float), and tuples (tuple) are passed by reference to functions, but since they are immutable, the original object cannot be changed inside the function.

This means that if you try to modify a parameter inside the function, for example, by assigning a new value, a new object will be created, and the original will remain unchanged.

Example:

def func(x):
    x = x + 1  # A new object is created, the original remains unchanged

num = 10
func(num)
print(num)  # Will output 10

Thus, immutable types behave as if they are passed by value, although technically a reference to the object is passed. This ensures safety from accidental data modification inside the function.

How do immutable data types behave when passed to a… - sobes.tech