Python List ‘sort()’ Method – Sorting Lists in Python Easily

Sorting Lists in Python Easily

In Python, there’s an easy way to sort lists: using the sort() method. This tutorial explains how to use sort(), with examples.

We’ve covered the following in Python:

Now it’s time to find out how to sort a list.

Syntax for the sort() Method

list.sort(reverse=True|False, key=sortFunction)

Note that:

  • ‘reverse’ should be a True/False boolean value and is optional
    • reverse=True will sort the list descending
    • The default is reverse=False
    • True/False values case sensitive in Python! You must capitalize the first letter when using them
  • ‘key’ is a function which defines the sorting conditions and is also optional

Sort List Alphabetically

When called on a list, the default behavior of sort is to sort the values in ascending order, numerically/alphabetically:

fruit = ['banana', 'cherry', 'apple']
fruit.sort() 
print(fruit) # ['apple', 'banana', 'cherry']

Sort List Descending

Set reverse=True to sort descending instead of ascending:

fruit = ['banana', 'cherry', 'apple']
fruit.sort(reverse=True) 
print(fruit) # ['cherry', 'banana', 'apple']

Sort List Using a Function

Custom sorting can be achieved by passing a function to sort():

# Defines a function which returns the length of given text
def countLettersFunction(text):
    return len(text)

# List of fruit

fruit = ['banana', 'cherry', 'apple', 'pear', 'fig']

# Sorted using the count letters function, ascending order

fruit.sort(key=countLettersFunction)

print(fruit) # ['fig', 'pear', 'apple', 'banana', 'cherry']

# And with a descending sort

fruit.sort(reverse=True, key=countLettersFunction)

print(fruit) # ['banana', 'cherry', 'apple', 'pear', 'fig']

Sort List of Dictionaries (Objects) by Attribute Value

# Defines a function which returns the colour attribute of a fruit
def colourFunction(fruit):
    return fruit['colour']

# List of fruit details in dictionaries

fruit = [
    {'name': 'Apple', 'colour': 'red'},
    {'name': 'Banana', 'colour': 'yellow'},
    {'name': 'Blueberry', 'colour': 'blue'},
    {'name': 'Cherry', 'colour': 'red'},
    {'name': 'Orange', 'colour': 'orange'}
]

fruit.sort(key=colourFunction) # Will sort by the result of colourFunction, ascending

print(fruit) # [
    # {'name': 'Blueberry', 'colour': 'blue'}, 
    # {'name': 'Orange', 'colour': 'orange'}, 
    # {'name': 'Apple', 'colour': 'red'}, 
    # {'name': 'Cherry', 'colour': 'red'},
    # {'name': 'Banana', 'colour': 'yellow'}
    #]
  • Dictionaries store data as key/value pairs
    • They are a kind of object, and behave similarly to how objects are used in JavaScript, PHP, and other languages: providing information for a single entity
  • Sort functions can return any type of value, and it will be sorted

Conclusion

Data sorting is one of the most useful tools in programming – from sorting shopping cart items by price for the user, to building decision-making processes based on collected data, you will use it a lot.

Simple sorting functions can be combined to create useful business logic to make your data work harder for you.

Check out our other Python explainers!

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *