0% found this document useful (0 votes)
15 views1 page

Trick Passing An Immutable by Reference

Cs

Uploaded by

Pooja Kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views1 page

Trick Passing An Immutable by Reference

Cs

Uploaded by

Pooja Kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Trick: Passing Integer by reference

In Python, we cannot explicitly pass an int (or any other immutable type)
by reference because integers are immutable. However, we can achieve similar
functionality by using mutable types, such as lists or custom objects, which can
store the integer value and thus be modified within a function.

Why You Can’t Pass Immutable Types by Reference In Python, im-


mutable types like int, float, str, and tuple cannot be modified in place.
When we pass an immutable object to a function, you are passing a reference
to the object, but since the object itself cannot be changed, any reassignment
within the function does not affect the original object.

Workarounds for Passing by Reference If we need to modify an integer


value within a function and see those changes reflected outside the function, we
can use a mutable container, such as a list to store the integer.

Using a List Here is an example using a list to pass an integer by reference:


def modify_value(lst):
lst[0] = 10

# Initialize a list with one integer element


value = [5]
print("Before:", value[0]) # Output: Before: 5

modify_value(value)
print("After:", value[0]) # Output: After: 10
While we cannot explicitly pass an immutable type like an int by reference in
Python, we can use a mutable container, such as a list or a custom object, to
achieve similar behavior. This allows us to modify the value within a function
and see those changes reflected outside the function.

You might also like