01

Introduction to sorting lists in Python

02

Sorting a list using the sorted() function

03

Sorting a list using the sort() method

04

Sorting a list in reverse order

05

Sorting a list of dictionaries

06

Sorting a list of tuples

07

Sorting a list of complex objects

08

Sorting a list using a key function

09

Sorting a list in place vs. creating a new sorted list

10

Conclusion

11

FAQs

Python is a versatile programming language that offers a range of useful features, including the ability to sort lists. Sorting a list is a common task in programming, and Python provides several methods for achieving this. In this article, we’ll explore **how to sort a list in Python** and the different methods available to you.

Sorting a list in Python involves arranging the elements in a particular order. The order can be ascending or descending, depending on the requirements of your program. Python provides several built-in functions and methods for sorting lists. These methods work differently based on the data types of the list elements.

The `sorted()`

function is a built-in function in Python that returns a sorted list. The `sorted()`

function can be used to sort lists of any data type. Here’s an example:

numbers = [5, 2, 8, 1, 9]sorted_numbers = sorted(numbers)print(sorted_numbers)

Output:

[1, 2, 5, 8, 9]

The `sort()`

method is a built-in method in Python that sorts a list in place. The `sort()`

method can only be used to sort lists of homogeneous data types, such as integers, floats, or strings. Here’s an example:

numbers = [5, 2, 8, 1, 9]numbers.sort()print(numbers)

Output:

[1, 2, 5, 8, 9]

You can sort a list in reverse order by passing the reverse parameter to the `sorted()`

function or the `sort()`

method. Here’s an example:

numbers = [5, 2, 8, 1, 9]sorted_numbers = sorted(numbers, reverse=True)print(sorted_numbers)

Output:

[9, 8, 5, 2, 1]

numbers = [5, 2, 8, 1, 9]numbers.sort(reverse=True)print(numbers)

Output:

[9, 8, 5, 2, 1]

You can sort a list of dictionaries based on a specific key by passing a key function to the `sorted()`

function or the `sort()`

method. Here’s an example:

students = [{"name": "John", "age": 20},{"name": "Mary", "age": 18},{"name": "Tom", "age": 22}]sorted_students = sorted(students, key=lambda x: x["age"])print(sorted_students)

Output:

[{'name': 'Mary', 'age': 18}, {'name': 'John', 'age': 20}, {'name': 'Tom', 'age': 22}]

You can sort a list of tuples based on a specific index by passing a key function to the `sorted()`

function or the `sort()`

method. Here’s an example:

students = [("John", 20), ("Mary", 18), ("Tom", 22)]sorted_students = sorted(students, key=lambda x: x[1])print(sorted_students)

Output:

[('Mary', 18), ('John', 20), ('Tom', 22)]

students = [("John", 20), ("Mary", 18), ("Tom", 22)]students.sort(key=lambda x: x[1])print(students)

Output:

[('Mary', 18), ('John', 20), ('Tom', 22)]

You can sort a list of complex objects based on multiple attributes by passing a key function to the `sorted()`

function or the `sort()`

method. Here’s an example:

class Student:def __init__(self, name, age, gpa):self.name = nameself.age = ageself.gpa = gpadef __repr__(self):return f"{self.name} ({self.age}), GPA: {self.gpa}"students = [Student("John", 20, 3.5),Student("Mary", 18, 4.0),Student("Tom", 22, 3.0)]sorted_students = sorted(students, key=lambda x: (x.gpa, x.age), reverse=True)print(sorted_students)

Output:

[Mary (18), GPA: 4.0, John (20), GPA: 3.5, Tom (22), GPA: 3.0]

A key function is a function that takes an element from the list and returns a value that will be used as the sort key. You can pass a key function to the `sorted()`

function or the `sort()`

method to sort a list based on a specific attribute. Here’s an example:

names = ["John", "Mary", "Tom", "Jerry"]sorted_names = sorted(names, key=len)print(sorted_names)

Output:

['Tom', 'John', 'Mary', 'Jerry']

names = ["John", "Mary", "Tom", "Jerry"]names.sort(key=len)print(names)

Output:

['Tom', 'John', 'Mary', 'Jerry']

The `sorted()`

function returns a new sorted list, while the `sort()`

method sorts the list in place. If you don’t want to modify the original list, use the `sorted()`

function. If you don’t need the original list, use the `sort()`

method to save memory. Here’s an example:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]sorted_numbers = sorted(numbers)print(sorted_numbers)print(numbers)

Output:

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

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]numbers.sort()print(numbers)

Output:

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

In this article, we’ve covered various ways to **sort a list in Python**. Whether you’re dealing with a list of integers, strings, dictionaries, tuples, or complex objects, Python provides built-in functions and methods to help you sort your data efficiently. Remember to choose the right sorting algorithm based on the size and complexity of your data, and consider the performance trade-offs between sorting in place and creating a new sorted list.

**What is the default sort order in Python?**The default sort order in Python is ascending order.**Can you sort a list of dictionaries by multiple keys?**Yes, you can sort a list of dictionaries by multiple keys by passing a tuple of keys to the`sorted()`

function or the`sort()`

method.**How do you sort a list of strings in reverse order?**You can sort a list of strings in reverse order bypassing the reverse parameter to the`sorted()`

function or the`sort()`

method.**What is the time complexity of the built-in**The time complexity of the built-in`sort()`

method in Python?`sort()`

method in Python is O(n log n).**How do you sort a list in descending order?**To sort a list in descending order, you can pass the reverse parameter with a value of True to the`sorted()`

function or the`sort()`

method.

We'll send you the best of our blog just once a month. We promise.

Learn Pain Less © 2024, All Rights Reserved.

Crafted with by Prolong Services

Quick Links

Legal Stuff

Social Media