0

I would like to know what the commas mean in line 5

def insertion_sort(items):
    for i in range(1, len(items)):
        j = i
        while j > 0 and items[j] < items[j-1]:
            items[j], items[j-1] = items[j-1], items[j]
            j -= 1
Paul
  • 26,170
  • 12
  • 85
  • 119
  • 4
    it means they are [tuples](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences) – MattDMo Nov 09 '14 at 03:58
  • possible duplicate of [Is there a standardized method to swap two variables in Python?](http://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python) – 101 Nov 09 '14 at 04:05
  • @MattDMo, not it means they are _sequences_. Not just tuples. – Burhan Khalid Nov 09 '14 at 04:09

4 Answers4

1

it means swap items[j] and items[j-1]

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

The comma on the right generates the tuple (b, a). The one on the left uses sequence unpacking to take the elements of the sequence on the right of the equals sign and bind them one by one to the names on the left. Hence the overall operation is to swap the objects bound to a and b.

more info

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

its like this,

>>> a, b = 2, 10
>>> temp = a
>>> a = b
>>> b = temp
>>> a
10
>>> b
2

In you case,

items[j], items[j-1] = items[j-1], items[j]

it will process like:-

 temp = items[j]
 item[j] = items[j-1j
 items[j-1] = temp
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
0

It is use to assign a value items[j]=items[j-1] and items[j-1] = items[j] in a single line you can write like items[j], items[j-1] = items[j-1], items[j] exchange the value of item here the like swap.

example :

          >>> a,b=10,20
          >>> a
          10
          >>> b
          20
         >>> a,b
         (10, 20)
Benjamin
  • 2,257
  • 1
  • 15
  • 24