2

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]
Ivan Borshchov
  • 3,036
  • 5
  • 40
  • 62

3 Answers3

4

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:

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
3

This line swaps element j and element i of x.

foobarbecue
  • 6,780
  • 4
  • 28
  • 54
2

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].

valentine
  • 57
  • 1
  • 8