pianist1119
pianist1119

Reputation: 319

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?

Upvotes: 8

Views: 11334

Answers (2)

eri
eri

Reputation: 3504

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]

Upvotes: 6

wim
wim

Reputation: 362507

Well, just look at the implementation of random.shuffle. Find it in a file called random.py, it's a pure python implementation and quite simple - just using a loop of assignments (with tuple unpacking).

def shuffle(self, x, random=None, int=int):
    """x, random=random.random -> shuffle list x in place; return None.

    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.

    Do not supply the 'int' argument.
    """

    if random is None:
        random = self.random
    for i in reversed(xrange(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random() * (i+1))
        x[i], x[j] = x[j], x[i]

Upvotes: 1

Related Questions