Reputation: 11
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
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
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
.
Upvotes: 1
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