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.

Python Sorted icon

✅ 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

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“