Issue
Without return statement any change inside a function should not be accessible right?(correct me if i am wrong) But this code gives output without a return statement
def my_fun(a):
a[0] = 'new value:'
a[1] = a[1] + 1
x = ['old value:', 99]
my_fun(x)
print (x[0], x[1])
i just ran this code and got out put as new value: 100 i am using python 3.6. Also will this work in any other programming language?
Solution
In Python, arguments are passed by reference, meaning that any modification made to them is retained after the call. However, reassigning an object changes the target of the reference, and any subsequent modifications cannot be retained. Consider the following example:
def foo(bar):
bar[0] = 2 # modification
bar = [] # reassigment
x = [1]
print(x)
foo(x)
print(x)
This outputs:
[1] [2]
Some objects, like tuples or integers, are immutable which means they can't be modified, and raise an exception when an attempt is made. They cannot be modified without being reassigned.
This is specific to Python. Java acts in a superficially similar fashion, but the implementation is very different: Objects are passed by reference and carry modifications over, whereas simple data types (int
, double
, char
, etc.) are copied and modifications don't carry over. C and C++ never modify an object, the only way to retain modifications on an object is to pass a pointer on the object to the function.
Answered By - Syncrossus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.