Code has been added to clipboard!

Making Python Sort Lists in Two Ways

Reading time 2 min
Published Feb 10, 2020
Updated Feb 10, 2020

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:

Example
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 reverse=True:

Example
pies = ['Pecan', 'Apple', 'Cherry', 'Keylime']
pies.sort(reverse=True)
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion
Coursera
Pros
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
Datacamp
Pros
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • 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 sorted method:

Example
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:

Example
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.lower as 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 key argument to specify one.

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 05/03/2021
3176 People Used
Only 97 Left
Rating
5.0