Mastering Python's sorted(): Sorting with Key and Lambda
Mastering Python's sorted(): Sorting with Key and Lambda ๐ข
The sorted() function is one of Python's most powerful tools for organizing data.
In this post, we'll explore everything from basic usage to advanced custom sorting using key and lambda.
✅ Basic Sorting
Start with sorting simple lists of numbers in ascending order.
# Basic list sorting
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 2, 5, 9]
✅ Descending Order
Use the reverse=True argument to flip the order.
# Sorting in descending order
desc = sorted(numbers, reverse=True)
print(desc) # [9, 5, 2, 1]
✅ Sorting with key Parameter
You can sort items based on a custom rule, like string length.
# Sorting by string length using key
words = ['apple', 'banana', 'kiwi', 'grape']
sorted_by_length = sorted(words, key=len)
print(sorted_by_length) # ['kiwi', 'apple', 'grape', 'banana']
✅ Using lambda for Custom Sorting
Sort more complex data like tuples using lambda to specify which element to sort by.
# Custom sorting with lambda
pairs = [('a', 3), ('b', 1), ('c', 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # [('b', 1), ('c', 2), ('a', 3)]
sorted() always returns a new list, leaving the original data unchanged.
Understanding key and lambda is crucial for mastering custom sorting logic in real-world applications.
Well-sorted data leads to well-structured thinking. Level up your Python with smart, readable sorting. You're building something powerful—keep going. ๐
Icons by Flaticon
Comments
Post a Comment