How To Sort List in Python

How to Sort List in Python

Sorting lists in Python is a common task that every programmer encounters. Python provides built-in functions that make sorting lists easy and efficient. In this article, we’ll explore different ways of sorting lists in Python.

Sorting a List using the sorted() Function

The sorted() function is a built-in function in Python that returns a new sorted list from the elements of an iterable. Here’s how to use it to sort a list in ascending order:

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

sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output:

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

The sorted() function also has an optional argument called reverse, which can be set to True to sort the list in descending order:

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

sorted_numbers = sorted(numbers, reverse=True)

print(sorted_numbers)

Output:

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

Sorting a List using the sort() Method

The sort() method is another built-in function in Python that can be used to sort a list in place. This means that the original list is modified, and the sorted list is not returned. Here’s how to use it:

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

numbers.sort()

print(numbers)

Output:

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

The sort() method also has an optional argument called reverse, which can be set to True to sort the list in descending order:

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

numbers.sort(reverse=True)

print(numbers)

Output:

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

Sorting a List of Tuples by the Second Element

Sometimes we may have a list of tuples, and we want to sort the list based on the second element of each tuple. We can achieve this by passing a lambda function as the key argument to the sorted() function:

students = [("Alice", 22), ("Bob", 19), ("Charlie", 21), ("David", 20)]

sorted_students = sorted(students, key=lambda student: student[1])

print(sorted_students)

Output:

[('Bob', 19), ('David', 20), ('Charlie', 21), ('Alice', 22)]

In the above example, we sorted the list of tuples based on the second element of each tuple, which represents the age of the student.

Sorting a List of Dictionaries by a Key

If we have a list of dictionaries, and we want to sort the list based on a specific key in each dictionary, we can use the key argument in the sorted() function:

students = [
    {"name": "Alice", "age": 22},
    {"name": "Bob", "age": 19},
    {"name": "Charlie", "age": 21},
    {"name": "David", "age": 20}
]

sorted_students = sorted(students, key=lambda student: student["age"])

print(sorted_students)

Output:

[{'name': 'Bob', 'age': 19}, {'name': 'David', 'age': 20}, {'name': 'Charlie', 'age': 21}, {'name': 'Alice', 'age': 22}]

In the above example, we sorted the list of dictionaries based on the age key of each dictionary.

Sorting a List of Objects

If we have a list of objects, and we want to sort the list based on a specific attribute of each object, we can use the attrgetter() function from the operator module:

from operator import attrgetter

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Student(name='{self.name}', age={self.age})"

students = [
    Student("Alice", 22),
    Student("Bob", 19),
    Student("Charlie", 21),
    Student("David", 20)
]

sorted_students = sorted(students, key=attrgetter("age"))

print(sorted_students)

Output:

[Student(name='Bob', age=19), Student(name='David', age=20), Student(name='Charlie', age=21), Student(name='Alice', age=22)]

In the above example, we defined a Student class and created a list of Student objects. We then used the attrgetter() function to sort the list based on the age attribute of each object.

Conclusion

In this article, we explored different ways to sort lists in Python. We learned how to use the sorted() function and the sort() method to sort lists in ascending or descending order. We also learned how to sort a list of tuples by the second element of each tuple, a list of dictionaries by a key, and a list of objects by a specific attribute. Sorting lists in Python is a fundamental skill that every programmer should master, as it is a common task in many applications.

Leave a Comment

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