I was recently learning how to use random.shuffle
in Python and I was surprised to see that the function shuffles the variable in place without returning anything. How is this acheived in the function? Looking at the random library's source code yielded no answer.
How can I write my own function that changes the variable in place without reassignment?
The word "change" is ambiguous in Python: we have two distinct types of "change" in Python. We can "change" a variable by changing which object that variable is pointing to. We do that through an assignment statement. We can also "change" an actual object through a mutation. Let's take a look at both types of change.
Python gives you a keyword named global to modify a variable outside its scope. Use it when you have to change the value of a variable or make any assignments. Let us try fixing the above code using the global keyword. See how we specify x as global using the global keyword in the third line.
I is works because of lists are mutable. You cant reassign any variable because it will be new variable. You cant modify immutable typed variable. You can modify mutable variable.
So:
>>> def addone(x):
... x += 1
>>> a = 2
>>> addone(a)
>>> a
2
>>> def addone(x):
... x.append(1)
...
>>> l=[2]
>>> addone(l)
>>> l
[2, 1]
>>> def addone(x):
... x = x + [1]
...
>>> li=[2]
>>> addone(li)
>>> li
[2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With