As I am going through the book Python Workshop, on the topic of Bubble sort algorithms, I came upon this snippet of code:
l = [5, 8, 1, 3, 2]
still_swapping = True
while still_swapping:
still_swapping = False
for i in range(len(l) - 1):
if l[i] > l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
still_swapping = True
As I understand the premise of the code, comparing the values one by one and replacing them in correct order, I do not understand what is happening here:
l[i], l[i+1] = l[i+1], l[i]
Of course, I can write such code myself, here is my beginner version:
l = [5, 8, 1, 3, 2]
still_swapping = True
while still_swapping:
still_swapping = False
for i in range(len(l) - 1):
if l[i] > l[i+1]:
temp = l[i]
l[i] = l[i+1]
l[i+1] = temp
still_swapping = True
print(l)
But the question is, what is that shortened version of the code that is provided in the book? What kind of operation is taking place? I don't understand the syntax here. Can't really find it in the previous chapters of the book.
Thanks in advance!
The only difference between your code and the shortened code is this line:
l[i], l[i+1] = l[i+1], l[i]
What this does is it assigns 2 objects at a time. For example,
a, b = c, d
assigns a = c
and b = d
at the same time.
This isn't limited to just variable assignments, it also works for for-loops:
for index, item in enumerate(lst):
This will iterate through the indexes and the item at the same time.
One last thing to note is that you can assign more than 2 at a time.
a, b, c = 1, 2, 3
will work as expected.
So this shortened code simply assigns l[i] = l[i+1]
and l[i+1] = l[i]
at the same time, thus eliminating the need for an extra line defining a temp variable.