Introduction
Programming fundamentally involves sorting data, and Python provides a robust and versatile built-in function called sorted(). This feature makes it simple and customizable to sort dictionaries, lists, tuples, and more.
Table of Contents
- What is the
sorted()Function in Python? - Syntax of
sorted() - Sorting Lists
- Sorting Tuples
- Sorting Dictionaries
- Customizing Sorts with the
keyParameter - Sorting in Descending Order
- Use cases and real-world examples
- Common Mistakes with
sorted() - Conclusion
1. What is the sorted() Function in Python?
Use Cases and Real-World ExamplesPython’s built-in sorted() method extracts a new sorted list from the contents of any iterable, such as a dictionary, tuple, or list.### 2. Syntax of sorted()
2. Syntax of sorted()
sorted(iterable, key=None, reverse=False)
iterable: The sequence you want to sort.key: A function that serves as a basis for sorting (e.g.,lenfor sorting by length).reverse: A Boolean to sort in descending order (True) or ascending order (False).
3. Sorting Lists
Sorting lists with sorted() is straightforward.
numbers = [4, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 4, 9]
4. Sorting Tuples
You may use sorted() to sort the contents of tuples, even if they are immutable. It will yield a list.
values = (5, 2, 8, 3)
sorted_values = sorted(values)
print(sorted_values) # Output: [2, 3, 5, 8]
5. Sorting Dictionaries
By default, `sorted()` only sorts dictionary keys.
my_dict = {'a': 2, 'c': 1, 'b': 3}
sorted_keys = sorted(my_dict)
print(sorted_keys) # Output: ['a', 'b', 'c']
6. Customizing Sorts with the key Parameter
You may specify custom sorting behavior, such sorting strings by length, using the `key` argument.
words = ["apple", "banana", "cherry"]
sorted_words = sorted(words, key=len)
print(sorted_words) # Output: ['apple', 'cherry', 'banana']
7. Sorting in Descending Order
Items are sorted in decreasing order using the `reverse=True` parameter.
scores = [99, 78, 85, 92]
sorted_scores = sorted(scores, reverse=True)
print(sorted_scores) # Output: [99, 92, 85, 78]
8. Real-world examples
Sorting a list of dictionaries by a specific key.
Sorting complex data structures for data analysis.
students = [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 90}]
sorted_students = sorted(students, key=lambda x: x['score'])
print(sorted_students)
# Output: [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 90}]
9. Common Mistakes with sorted()
- Trying to use
sorted()directly on non-iterables. - Not setting
reverse=Truefor descending order.
Conclusion
The sorted() function in Python is a versatile tool for arranging data efficiently. Its customizable parameters make it suitable for various scenarios, from basic lists to more complex data structures.