1.6. Sorting a List

Sorting Elements in a List

sort()

We can sort a list using sort() method. This kind of sorting will permanently change the order of the list. See the following two examples:

sorted()

We use this method if we want to sort the list temporarily. This doesn't affect the actual order of the list. Let's try using our languages list:

reverse()

We can use this method to reverse the order of the list (the last one will be the first).

Exercise 1.6

Around the World
Say you visited several countries in these orders: Indonesia, Japan, Greece, Belgium, Saudi Arabia, Vietnam, and America.

a. Store those locations in a list called country_list.

b. Print your list in its original order using print(country_list).

c. Use sorted() to print your list without modifying the actual list.

d. Show that your list is still in its original order by printing it again.

e. Use sorted(list,reverse=True) to print your list in reverse alphabetical order without changing the order of the original list. Save it in a variable.

f. Show that countries_list is still in its original order by printing it again.

g. Use reverse() to change the order of the list you made in e. Then print it.

h. Use sort() to change your list so it's stored in alphabetical order. Print the list to show that its order has been changed.

i. Use sort() to change your list so it's stored in reverse alphabetical order. Print the list to show that its order has changed.