Sorting Lists

Introduction to Sorting

Sorting a list means arranging its elements in a specific order, such as ascending or descending. Python provides simple ways to sort lists using the sort() method or the sorted() function.


1. Using the sort() Method

Example:

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

numbers.sort()

print(numbers)  

# Output: [1, 2, 5, 5, 6, 9]


Descending Order: To sort in descending order, use the parameter reverse=True.

Example:

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

numbers.sort(reverse=True)

print(numbers)  

# Output: [9, 6, 5, 5, 2, 1]



2. Using the sorted() Function

Example:

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

sorted_numbers = sorted(numbers)

print(sorted_numbers)  

# Output: [1, 1, 3, 4, 5, 9]

print(numbers)  

# Original list remains unchanged: [3, 1, 4, 1, 5, 9]


Descending Order: Use reverse=True with sorted().

Example:

words = ["banana", "apple", "cherry"]

sorted_words = sorted(words, reverse=True)

print(sorted_words)  

# Output: ['cherry', 'banana', 'apple']



3. Sorting with Custom Criteria

Sometimes, you may need to sort a list based on a specific rule. You can use the key parameter to define custom sorting logic.

Example: Sorting by String Length:

words = ["apple", "fig", "banana", "kiwi"]

words.sort(key=len)

print(words)  

# Output: ['fig', 'kiwi', 'apple', 'banana']



Practice Exercises


Challenge Solution Example

Sorting a List of Dictionaries:

students = [

    {"name": "Alice", "grade": 85},

    {"name": "Bob", "grade": 72},

    {"name": "Charlie", "grade": 90}

]


# Sort by grade

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

print(students)

# Output: [{'name': 'Bob', 'grade': 72}, {'name': 'Alice', 'grade': 85}, {'name': 'Charlie', 'grade': 90}]



Conclusion

Sorting is an essential skill in Python, useful for organizing and managing data. Practice using sort(), sorted(), and custom sorting to become proficient.