0

Hi I have a question about the if statement int he for j loop. I understand that you swap the smaller value with the bigger value but I don't understand why it is written as waarde, rij[j] = rij[j], waarde. is the comma some sort of swapper in Python?

 def insertionsort(rij):            
     for i in range(len(rij)):         
         waarde = rij[i]               
         for j in range(0, i):        
             if waarde<rij[j]:        
                 waarde, rij[j] = rij[j], waarde   
         rij[i] = waarde               
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80

2 Answers2

1

In Python,

a, b = b, a

effectively swaps the values a and b. More precisely, the name a will now reference the value that was previously referenced by b and vice versa.

This is called tuple packing/unpacking. The comma builds tuples; the swapping is done by the =.

What happens "behind the scenes" is this:

  • The tuple b, a is evaluated. You can imagine the result of this evaluation to be stored in an unnamed temporary variable. Let's call that variable temp.
  • The assignment operator = now causes temp to be assigned to the name(s) on the left side of the =. If there had been just one name on the left, as in x = b, a, then x would have been assigned the tuple b, a.
  • Since there is more than one name on the left side, temp will be "unpacked" into these names in sequence.
  • a will be assigned the value of temp[0] (which holds the value that b pointed to), and b will be assigned the value of temp[1].

Note that the number of names on both sides must match:

>>> a = 1
>>> b = 2
>>> c = 3
>>> a, b = c, b, a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

But you can use the tuple packing operator * to tell Python to pack the remaining values into a single name:

>>> a, *b = c, b, a
>>> a
3
>>> b
[2, 1]
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

In Python you can assign multiple varialbes like this:

a, b = "A", "B"

This is saying: assign the first value on the right of the = to the first name on the left of the =, and assign the second value on the right of the = to the second name on the left of the =.

You can also do it with three or more vars:

a, b, c, d = "A", "B", "C", "D"

You can use this feature to swap the values of variables:

a, b = b, a

Now when you print a you get "B" and when you print b you get "A".

gitaarik
  • 42,736
  • 12
  • 98
  • 105