Ivan Borshchov
Ivan Borshchov

Reputation: 3549

Commas in python?

I want to understand function from random.py: Why the last line looks so?

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

Why it's not single:

x[j] = x[j]

Upvotes: 2

Views: 1196

Answers (3)

johnsyweb
johnsyweb

Reputation: 141790

a, b = b, a is idiomatic Python for "swap a and b".

x[i], x[j] = x[j], x[i]  # Swaps x[i] and x[j]

Related Stack Overflow posts:

Upvotes: 4

valentine
valentine

Reputation: 57

this is shorthand for:

x[j]=x[i]
x[i]=x[j]

Notice though, if you were to do it in two lines, the value of x[j] would be overwritten by the new value of x[i]. By doing it in one line the way the authors did, the new value of x[j] will be set to the old value of x[i] and the new value of x[i] will be set to the old value of x[j].

Upvotes: 2

foobarbecue
foobarbecue

Reputation: 7060

This line swaps element j and element i of x.

Upvotes: 3

Related Questions