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
The sort() method sorts the list in place, meaning the original list is changed.
By default, sort() arranges elements in ascending order.
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
The sorted() function returns a new sorted list without modifying the original list.
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
Basic Sorting:
Create a list of 10 random numbers.
Sort the list in ascending order and print it.
Sort the list in descending order and print it.
Alphabetical Order:
Create a list of five of your favorite fruits.
Sort the list alphabetically and print it.
Custom Sorting:
Create a list of words with different lengths.
Sort the list by the length of the words and print the result.
Preserve Original List:
Create a list of numbers.
Use sorted() to create a new sorted list.
Print both the original and the sorted lists.
Challenge Exercise:
Create a list of dictionaries, each representing a student with a name and a grade (e.g., {"name": "Alice", "grade": 85}).
Sort the list by grade in ascending order.
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.