Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Change Variable In Place

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?

like image 597
pianist1119 Avatar asked Mar 26 '14 23:03

pianist1119


People also ask

What is change () in Python?

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.

How do you modify an outside variable in Python?

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.


1 Answers

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]
like image 116
eri Avatar answered Nov 14 '22 09:11

eri