Unlock the Power of Python’s sorted() Method
When working with data in Python, being able to sort and organize it efficiently is crucial. That’s where the sorted() method comes in – a powerful tool that helps you tame even the most unruly datasets.
What Does sorted() Do?
The sorted() method takes an iterable (such as a list, tuple, or string) and returns a new list with its elements in ascending order. But here’s the catch: it doesn’t modify the original iterable. Instead, it creates a brand new list with the sorted elements.
The Syntax of sorted()
The basic syntax of sorted() is simple: sorted(iterable)
. However, it also accepts two optional parameters: reverse
and key
.
key
: a function that determines the basis for sort comparison. Defaults to <code(none)< code=””>.</code(none)<>reverse
: a boolean that decides the sorting order. IfTrue
, the list is sorted in descending order.
Sorting in Action
Let’s see sorted() in action:
print(sorted([3, 1, 2, 4])) # returns [1, 2, 3, 4]
print(sorted((3, 1, 2, 4))) # returns [1, 2, 3, 4]
print(sorted({'c': 3, 'a': 1, 'b': 2, 'd': 4})) # returns ['a', 'b', 'c', 'd']
print(sorted({3, 1, 2, 4})) # returns [1, 2, 3, 4]
Reversing the Order
Want to sort in descending order instead? Simply add the reverse
parameter: sorted(iterable, reverse=True)
.
Sorting with a Key Function
The key
parameter allows you to sort based on a specific criterion. For example, you can sort a list of strings by their length using sorted(iterable, key=len)
.
strings = ['hello', 'world', 'abc']
print(sorted(strings, key=len)) # returns ['abc', 'hello', 'world']
User-Defined Key Functions
You can also use user-defined functions as the key function. For instance, if you have a list of tuples representing personal information, you can sort by age using a custom function:
def get_age(person):
return person[1]
personal_info = [('John', 25), ('Alice', 30), ('Bob', 20)]
print(sorted(personal_info, key=get_age)) # returns [('Bob', 20), ('John', 25), ('Alice', 30)]
Combining Key and Reverse Parameters
Want to sort by age in descending order? No problem: sorted(personal_info, key=get_age, reverse=True)
.
The Difference Between sorted() and sort()
While sorted()
returns a new list with sorted elements, the sort()
method modifies the original list directly and doesn’t return any values.
For example:
my_list = [3, 1, 2, 4]
my_list.sort()
print(my_list) # returns [1, 2, 3, 4]
my_list = [3, 1, 2, 4]
sorted_list = sorted(my_list)
print(my_list) # returns [3, 1, 2, 4]
print(sorted_list) # returns [1, 2, 3, 4]
Learn more about Python’s sorting capabilities.