Sorting lists and strings in Python
Coding with Python
🕑 This lesson will take about 10 minutes
Sorting lists using the sort() method
The sort() method is used to sort the values in a list (in ascending or descending order). Let’s say we have a list called numbers and we wanted it sorted into numeric order. We can write numbers.sort() and the values will be sorted. The method takes an optional parameter which we can use if we want to sort a list into reverse order. For example, numbers.sort(reverse=True) can be used to sort the list into reverse order. The sort() method can be used to sort values of different data types (eg. strings in ascending or descending order).
Check out the different examples below.
Sorting strings with the sorted() function
Strings can also be sorted into ascending or descending order. With strings, we use the sorted() function. It takes the string we wish to sort as a parameter and also has a second optional parameter to specify if the string should be sorted in reverse order. Check out the examples below.
Review questions
What happens if you attempt to use the sort() method on a tuple?
What happens if you sort a string using the sorted() function without also writing ''.join before the sorted() function call? How will the string be displayed?
What happens if you attempt to use the sort() method on a list that contains values of different data types (eg. integer, string, Boolean)?
Next lesson: Dictionaries