TL;DR – depending on the method you choose, you can either sort an existing list in Python, or create a sorted one without changing the original.
How to sort a list in Python
The easiest way to make Python sort lists is using the
sort function. It will modify the original list without creating a new one:
pies = ['Pecan', 'Apple', 'Cherry', 'Keylime'] pies.sort()
The system will sort numbers in an ascending order and strings in an alphabetical order. You can reverse this by including an optional argument
pies = ['Pecan', 'Apple', 'Cherry', 'Keylime'] pies.sort(reverse=True)
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid certificates of completion
- Great user experience
- Offers quality content
- Very transparent with their pricing
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
Creating a Python sorted list
In some cases, you might want to leave the original list untouched, but still need a sorted version of it. To achieve this, use the
pies = ['Pecan', 'Apple', 'Cherry', 'Keylime'] sorted_list = sorted(pies)
Just like with
sort, you can use the
reverse argument to make Python sort list in reverse order. You can also sort it according to a different criteria by using an optional
key argument and defining a basis for sorting.
In the example below, we create a Python sorted list according to the length of the string:
pies = ['Blackberries', 'Pecan', 'Lime', 'Cinammon'] sorted_list = sorted(pies, key=len)
Python sort list: useful tips
- Sorting a list in alphabetical order can be performed wrong when you're dealing with both uppercase and lowercase letters, and the system treats them as if they were different in value. To work around this, use the key argument and define
str.loweras the basis for sorting.
- When working with tuples, the system will only see their first elements and sort accordingly. If you want your tupples sorted in a different manner, use the
keyargument to specify one.