Omar Sherief
Omar Sherief

Reputation: 11

What do the commas mean in a statement like: a,b=b,a?

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

Upvotes: 0

Views: 200

Answers (4)

Benjamin
Benjamin

Reputation: 2286

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)

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

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

Upvotes: 1

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

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

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113948

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

Upvotes: 1

Related Questions