How to pass a value by pass value in function

like in c++ we have a method to pass value by value or by reference so in python how can we use pass by value method in python as I have to use .copy() so is there any other way to pass by value in python so it does not get edit when we edit in the recursion in my code plz explain.

Hi @Jan19LPN0013,

The behavior of Python is quite different from C++. Simply put:
If you’re mutating an object, it behaves as Call by reference. If you assign new objects to the passed variable, the original link is broken and you can no longer make changes to the original variable.
Quoting Tutorials Point:
" Python uses a mechanism, which is known as " Call-by-Object ", sometimes also called " Call by Object Reference " or " Call by Sharing "

If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like C all-by-value . It’s different, if we pass mutable arguments.

All parameters (arguments ) in the Python language are passed by reference . It means if you change what a parameter refers to within a function, the change also reflects back in the calling function."

Look at this link for more a code sample.

so now what is the solution of my given code how to pass feature so that it does not get editted after recursion another than .copy()

Ways to achieve what you’re trying to do:

new_list = old_list.copy()

new_list = old_list[:]

new_list = list(old_list)

i am trying to say it is not possible to pass by value in python without using this type of function like in c++

No, it’s not. You have to use some auxiliary function (especially for mutable objects).

ohk thankyou sir for your support

1 Like

Glad I could be of help!

In Python, the method of passing arguments to functions is neither strictly call-by-value nor call-by-reference. Instead, it uses a mechanism called “call-by-object-reference” or “call-by-sharing.” When you pass an immutable object as an argument to a function, it behaves like call-by-value. When you pass a mutable object as an argument to a function, it behaves like call-by-reference. If you modify a mutable object directly (e.g., appending an element to a list) within the function, it will affect the original object passed as an argument. This is because both the function parameter and the original object reference the same underlying object. If you reassign a new value to a parameter that originally referred to an immutable object within the function, it creates a new object. However, it does not affect the original object passed as an argument.