Hello everyone;
I am new to Python. How can we explain this code step by step. I couldn't understand some parts.

``````myList=[43,21,12,80,3,2,35]
end=len(myList)-1
while (end!=-1):
swapped=-1
for i in range(0,end):
if myList[i]>myList[i+1]:
temp=myList[i]
myList[i]=myList[i+1]
myList[i+1]=temp
swapped=i
end=swapped
print(myList)
``````

## Featured Replies in this Discussion

• You can insert a print statement for testing the progress, and see how the higher values bubble to the end and lower values bubble to the start of the list: ... Also the C type swap ... can be replaced with a Python tuple swap myList[i+1], myList[i] = myList[i], myList[i+1]
Post Contains: Code

You can insert a print statement for testing the progress, and see how the higher values bubble to the end and lower values bubble to the start of the list:

``````myList=[43,21,12,80,3,2,35]
print(myList)
print('-'*30)

end = len(myList)-1
while (end != -1):
swapped = -1
for i in range(0, end):
if myList[i] > myList[i+1]:
temp = myList[i]
myList[i] = myList[i+1]
myList[i+1]= temp

print(myList)  # test print to follow progress of sort

swapped = i
end = swapped

print('-'*30)
print(myList)

'''
[43, 21, 12, 80, 3, 2, 35]
------------------------------
[21, 43, 12, 80, 3, 2, 35]
[21, 12, 43, 80, 3, 2, 35]
[21, 12, 43, 3, 80, 2, 35]
[21, 12, 43, 3, 2, 80, 35]
[21, 12, 43, 3, 2, 35, 80]
[12, 21, 43, 3, 2, 35, 80]
[12, 21, 3, 43, 2, 35, 80]
[12, 21, 3, 2, 43, 35, 80]
[12, 21, 3, 2, 35, 43, 80]
[12, 3, 21, 2, 35, 43, 80]
[12, 3, 2, 21, 35, 43, 80]
[3, 12, 2, 21, 35, 43, 80]
[3, 2, 12, 21, 35, 43, 80]
[2, 3, 12, 21, 35, 43, 80]
------------------------------
[2, 3, 12, 21, 35, 43, 80]
'''
``````

Also the C type swap

``````        temp = myList[i]
myList[i] = myList[i+1]
myList[i+1]= temp
``````

can be replaced with a Python tuple swap

myList[i+1], myList[i] = myList[i], myList[i+1]

Let us know if this helped.

Question Answered as of 2 Years Ago by vegaseat and sneekula
You