How to Sort List in Python: A Step-by-Step Guide for Beginners

sort list in Python
Table of Contents

Introduction

Sorting is a fundamental idea in programming, and Python makes it quite simple with its built-in functions. Whether you’re sorting numbers, characters, or complex data structures, knowing how to sort list in Python will help you code more efficiently.

In this step-by-step article, we’ll look at numerous ways to sort list in Python, including both built-in and custom sorting strategies. By the conclusion, you’ll understand sorting in Python and be able to apply these approaches in real-world applications.

Why Sorting is Important in Python?

Sorting helps to organise data, making it easier to explore, analyse, and make decisions. Knowing how to sort list in Python is essential for managing financial transactions, ranking students by grades, and arranging product pricing on an e-commerce platform.

How to Sort List in Python: A Beginner’s Ultimate Guide to Mastering Sorting Techniques

1. Using the sort() Method

The sort() method is the easiest way to sort a list in Python. It sorts the list in place, meaning the original list is modified.

Syntax:

list.sort()

Example:

numbers = [5, 2, 9, 1, 5, 6]

numbers.sort()

print(numbers)

Output:

[1, 2, 5, 5, 6, 9]

Key Points:
  • Modifies the original list
  • Sorts in ascending order by default
  • Works on lists containing numbers or strings
Sorting in Descending Order

If you want to sort in descending order, use the reverse=True parameter.

numbers.sort(reverse=True)

print(numbers)

Output:

[9, 6, 5, 5, 2, 1]

2. Using the sorted() Function

Unlike sort(), the sorted() function returns a new sorted list without modifying the original.

Syntax:

sorted_list = sorted(original_list)

Example:

numbers = [5, 2, 9, 1, 5, 6]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output:

[1, 2, 5, 5, 6, 9]

Why Use sorted()?
  • It does not modify the original list
  • Can be used on any iterable (not just lists)

3. Sorting Lists with a Custom Key

Python’s sorting methods support custom sorting via the key parameter. This is handy for sorting complex data structures like as tuples and dictionaries. 

Example: Sorting a List of Tuples

students = [(“Alice”, 25), (“Bob”, 20), (“Charlie”, 23)]

students.sort(key=lambda x: x[1])

print(students)

Output:

[(‘Bob’, 20), (‘Charlie’, 23), (‘Alice’, 25)]

Here, the list is sorted based on age (the second element in the tuple).

4. Sorting Strings Alphabetically

Python can also sort lists of strings effortlessly.

names = [“John”, “Alice”, “Bob”]

names.sort()

print(names)

Output:

[‘Alice’, ‘Bob’, ‘John’]

For case-insensitive sorting, use str.lower as the key:

names.sort(key=str.lower)

Also Read – 10 Useful Tools For Developer Needed

5. Sorting Lists with Mixed Cases

Sorting a list of uppercase and lowercase letters may produce unexpected results. To guarantee that the order is consistent, sort all components in lowercase. 

words = [“banana”, “Apple”, “orange”]

words.sort(key=str.lower)

print(words)

Output:

[‘Apple’, ‘banana’, ‘orange’]

6. Sorting Lists in Reverse Order

Both sort() and sorted() support reverse sorting using reverse=True.

numbers = [3, 1, 4, 1, 5, 9]

print(sorted(numbers, reverse=True))

Output:

[9, 5, 4, 3, 1, 1]

7. Sorting Lists with operator.itemgetter()

When sorting by multiple criteria, operator.itemgetter() provides a cleaner approach.

from operator import itemgetter

students = [(“Alice”, 25, 90), (“Bob”, 20, 85), (“Charlie”, 23, 95)]

students.sort(key=itemgetter(1, 2))

print(students)

Output:

[(‘Bob’, 20, 85), (‘Charlie’, 23, 95), (‘Alice’, 25, 90)]

8. Sorting Lists with functools.cmp_to_key()

For advanced sorting, cmp_to_key() allows defining custom comparison logic.

from functools import cmp_to_key

def compare(a, b):

    return a – b

numbers = [5, 2, 9, 1, 5, 6]

numbers.sort(key=cmp_to_key(compare))

print(numbers)

9. Sorting a List of Dictionaries

Sorting dictionaries within a list is easy with key=lambda.

people = [{“name”: “Alice”, “age”: 25}, {“name”: “Bob”, “age”: 20}]

people.sort(key=lambda x: x[“age”])

print(people)

Output:

[{‘name’: ‘Bob’, ‘age’: 20}, {‘name’: ‘Alice’, ‘age’: 25}]

Conclusion

Sorting is an essential skill in Python, and learning it will significantly increase your programming productivity. Whether you’re sorting numbers, texts, or complex data structures, Python has robust and versatile sorting methods.

Now that you’ve learnt how to sort a list in Python, use these techniques in real-world situations. Experiment with different ways and tweak your code to improve performance!

Related Articles