Home » Python : Sorting Lists

Python : Sorting Lists

Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Oracle Java Certification
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests

In Python, sorting lists is a common task, and Python provides several ways to sort lists efficiently.

Python allows you to sort lists either in-place (modifying the original list) or return a new sorted list without modifying the original.

You can also sort lists of numbers, strings, and even more complex data structures like lists of dictionaries, using different sorting criteria.

In this tutorial, we will cover different ways to sort lists using various methods such as sort(), sorted(), custom sorting using key functions, and reverse sorting.

 

1. Using the sort() Method (In-Place Sorting)

The sort() method sorts the list in place, meaning it modifies the original list. This method does not return a new list; it changes the order of the elements in the existing list.

Example: Sorting a List of Numbers

# Example: Sorting a list of numbers using sort()
numbers = [5, 3, 8, 1, 2]

# Sort the list in place
numbers.sort()

# Print the sorted list
print(numbers)  # Output: [1, 2, 3, 5, 8]

In this example:

The sort() method sorts the list of numbers in ascending order, modifying the original list.

Example: Sorting a List of Strings

# Example: Sorting a list of strings using sort()
fruits = ["apple", "banana", "cherry", "date"]

# Sort the list in place
fruits.sort()

# Print the sorted list
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'date']

In this example:

The sort() method sorts the list of strings in alphabetical order.

2. Using the sorted() Function (Return a New Sorted List)

The sorted() function returns a new sorted list, leaving the original list unchanged. This is useful when you want to preserve the original list and only work with a sorted version of it.

Example: Sorting a List of Numbers with sorted()

# Example: Using sorted() to sort a list of numbers
numbers = [5, 3, 8, 1, 2]

# Return a new sorted list
sorted_numbers = sorted(numbers)

# Print both lists
print("Original list:", numbers)        # Output: [5, 3, 8, 1, 2]
print("Sorted list:", sorted_numbers)   # Output: [1, 2, 3, 5, 8]

In this example:

The sorted() function returns a new sorted list, while the original list remains unchanged.

3. Sorting in Reverse Order

Both the sort() method and the sorted() function allow you to sort lists in reverse order by setting the reverse parameter to True.

Example: Sorting a List in Reverse Order

# Example: Sorting a list of numbers in reverse order using sort()
numbers = [5, 3, 8, 1, 2]

# Sort the list in reverse order in place
numbers.sort(reverse=True)

# Print the reversed sorted list
print(numbers)  # Output: [8, 5, 3, 2, 1]

Example: Using sorted() to Sort in Reverse Order

# Example: Using sorted() to sort a list in reverse order
numbers = [5, 3, 8, 1, 2]

# Return a new sorted list in reverse order
sorted_numbers = sorted(numbers, reverse=True)

# Print the sorted list
print(sorted_numbers)  # Output: [8, 5, 3, 2, 1]

In these examples:

The reverse=True argument sorts the list in descending order.

4. Sorting Lists with the key Parameter

The sort() method and sorted() function both accept a key parameter, which allows you to define a custom sorting order. The key parameter takes a function that returns a value that is used for sorting.

Example: Sorting by String Length

# Example: Sorting a list of strings by length
fruits = ["apple", "banana", "cherry", "date"]

# Sort by length of the strings
fruits.sort(key=len)

# Print the sorted list
print(fruits)  # Output: ['date', 'apple', 'banana', 'cherry']

In this example:

The key=len argument sorts the list by the length of the strings.
Example: Sorting by Absolute Value

# Example: Sorting a list of numbers by absolute value
numbers = [-3, 2, -5, 8, -1]

# Sort by absolute value
sorted_numbers = sorted(numbers, key=abs)

# Print the sorted list
print(sorted_numbers)  # Output: [-1, 2, -3, -5, 8]

In this example:

The key=abs argument sorts the list based on the absolute values of the numbers.

5. Sorting Lists of Tuples or Complex Data

You can use the key parameter to sort more complex data, such as lists of tuples or dictionaries, by specific elements or attributes.

Example: Sorting a List of Tuples by the Second Element

# Example: Sorting a list of tuples by the second element
points = [(1, 2), (3, 1), (5, 7), (4, 0)]

# Sort by the second element of each tuple
points.sort(key=lambda x: x[1])

# Print the sorted list
print(points)  # Output: [(4, 0), (3, 1), (1, 2), (5, 7)]

In this example:

The key=lambda x: x[1] sorts the list of tuples by the second element in each tuple.

Example: Sorting a List of Dictionaries by a Specific Key

# Example: Sorting a list of dictionaries by the 'age' key
people = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 20}
]

# Sort by the 'age' key
sorted_people = sorted(people, key=lambda x: x["age"])

# Print the sorted list
for person in sorted_people:
    print(person)

# Output:
# {'name': 'Charlie', 'age': 20}
# {'name': 'Alice', 'age': 25}
# {'name': 'Bob', 'age': 30}

In this example:

The key=lambda x: x[“age”] sorts the list of dictionaries by the age key.

6. Sorting with Multiple Criteria

You can sort a list by multiple criteria by passing a tuple or list of keys to the key function.

Example: Sorting a List of Tuples by Two Elements

# Example: Sorting by multiple criteria (first and second elements)
points = [(1, 2), (3, 1), (5, 7), (4, 0), (1, 1)]

# Sort by the first element, then by the second element
points.sort(key=lambda x: (x[0], x[1]))

# Print the sorted list
print(points)  # Output: [(1, 1), (1, 2), (3, 1), (4, 0), (5, 7)]

In this example:

The key=lambda x: (x[0], x[1]) sorts the list first by the first element of each tuple, and if two tuples have the same first element, it then sorts by the second element.

7. Case-Insensitive Sorting

By default, Python sorts strings in a case-sensitive manner, meaning that uppercase letters come before lowercase letters.

To sort strings in a case-insensitive manner, you can use str.lower as the key function.

Example: Case-Insensitive Sorting

# Example: Sorting strings in a case-insensitive manner
fruits = ["Apple", "banana", "Cherry", "date"]

# Sort case-insensitively
fruits.sort(key=str.lower)

# Print the sorted list
print(fruits)  # Output: ['Apple', 'banana', 'Cherry', 'date']

In this example:

The key=str.lower argument sorts the list of strings without regard to case, treating uppercase and lowercase letters as equal.

8. Sorting with Custom Functions

You can pass any custom function to the key parameter to sort lists based on complex criteria.

Example: Sorting Based on the Last Character of Strings

# Example: Sorting strings by their last character
words = ["apple", "banana", "cherry", "date"]

# Sort by the last character of each word
words.sort(key=lambda x: x[-1])

# Print the sorted list
print(words)  # Output: ['banana', 'apple', 'date', 'cherry']

In this example:

The key=lambda x: x[-1] sorts the list based on the last character of each string.

Summary

sort() sorts a list in place, modifying the original list, while sorted() returns a new sorted list, leaving the original list unchanged.
You can sort lists in reverse order by setting the reverse=True argument.
The key parameter allows you to sort lists based on custom criteria, such as sorting by the length of strings, absolute values, or specific elements of tuples or dictionaries.
You can sort strings in a case-insensitive manner using str.lower as the key function.
Sorting with custom functions allows you to define complex sorting behavior, such as sorting by the last character of strings or sorting by multiple criteria.

By mastering these sorting techniques, you can efficiently sort lists in Python for various data types and structures.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More