3. Module 2 Sorting simple lists
Sorting a list
my_list = [8, 10, 6, 2, 4] # list to sort
swapped = True # It's a little fake, we need it to enter the while loop.
while swapped:
swapped = False # no swaps so far
for i in range(len(my_list) - 1):
if my_list[i] > my_list[i + 1]:
swapped = True # a swap occurred!
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
print(my_list)
4. Module 2 Sorting simple lists
Ready-to-use tools
Python has its own
sorting mechanisms: .sort()
my_list = [8, 10, 6, 2, 4] # list to sort
swapped = True # It's a little fake, we need it to enter the while loop.
my_list.sort()
print(my_list)
5. Module 2 Sorting simple lists
Key takeaways
sort()
•to sort elements
of a list
reverse()
•to reverse the list