[Python] Understanding the sorted() Function in Python — Guide and Examples
Hello, this is BlockDMask.
Today we’ll explore Python’s built-in sorted()
function, which lets you sort any iterable and return a new list.
If you’re looking for the list.sort()
method instead, check out [this post on list.sort()].
<Table of Contents>
- What is sorted()?
- Example 1: Sorting a List of Numbers
- Example 2: Sorting Strings Case-Insensitive
- Example 3: Sorting Tuples by Second Element
- Example 4: Sorting Dictionary Keys and Items
- Example 5: Sorting Dictionary by Value
- Bonus Tip: Sorting Custom Objects
1. What is sorted()?
The sorted()
function takes any iterable—like a list, tuple, string, or dict—and returns a new, sorted list:
sorted(iterable)
sorted(iterable, reverse=True)
sorted(iterable, key=func)
sorted(iterable, key=func, reverse=True)
- iterable: any object you can loop over (list, tuple, string, dict).
- key: a function that extracts a comparison key from each element.
- reverse:
False
for ascending (default),True
for descending.
Unlike list.sort()
, which modifies the original list, sorted()
preserves it and returns the sorted result.
2. Example 1: Sorting a List of Numbers
# BlockDMask example: numbers
prices = [19.99, 5.99, 12.49, 99.95, 0.99]
ascending = sorted(prices) # default ascending
descending = sorted(prices, reverse=True)
print("original prices:", prices) # original unchanged
print("ascending :", ascending)
print("descending :", descending)
# output:
# original prices: [19.99, 5.99, 12.49, 99.95, 0.99]
# ascending : [0.99, 5.99, 12.49, 19.99, 99.95]
# descending : [99.95, 19.99, 12.49, 5.99, 0.99]
Why? By default, sorted()
orders floats from smallest to largest; reverse=True
flips that order.
3. Example 2: Sorting Strings Case-Insensitive
# DMask example: cities
cities = ["London", "amsterdam", "Berlin", "copenhagen"]
sorted_case = sorted(cities, key=str.lower)
print("original:", cities)
print("sorted_ci:", sorted_case)
# output:
# original: ['London', 'amsterdam', 'Berlin', 'copenhagen']
# sorted_ci: ['amsterdam', 'Berlin', 'copenhagen', 'London']
Why? We pass key=str.lower
so that uppercase/lowercase differences don’t affect the alphabetical order.
4. Example 3: Sorting Tuples by Second Element
# Block example: scores
student_scores = [("Alice", 88), ("Bob", 95), ("Charlie", 78), ("Diana", 90)]
by_score = sorted(student_scores, key=lambda x: x[1])
print("sorted by score:", by_score)
# output:
# sorted by score: [('Charlie', 78), ('Alice', 88), ('Diana', 90), ('Bob', 95)]
Why? The lambda x: x[1]
tells sorted to compare the second item (the score) of each tuple.
5. Example 4: Sorting Dictionary Keys and Items
# DMask example: inventory
inventory = {"apples": 50, "bananas": 20, "oranges": 30}
# Sort keys
keys_sorted = sorted(inventory)
# Sort items (key, value) pairs
items_sorted = sorted(inventory.items())
print("keys_sorted :", keys_sorted)
print("items_sorted:", items_sorted)
# output:
# keys_sorted : ['apples', 'bananas', 'oranges']
# items_sorted: [('apples', 50), ('bananas', 20), ('oranges', 30)]
Why?
• sorted(inventory)
sorts the dictionary’s keys by default.
• sorted(inventory.items())
returns a list of (key, value) tuples sorted by key.
6. Example 5: Sorting Dictionary by Value
# BlockDMask example: inventory by stock
inv_by_stock = sorted(inventory.items(), key=lambda kv: kv[1])
inv_by_stock_desc = sorted(inventory.items(), key=lambda kv: kv[1], reverse=True)
print("by stock asc :", inv_by_stock)
print("by stock desc:", inv_by_stock_desc)
# output:
# by stock asc : [('bananas', 20), ('oranges', 30), ('apples', 50)]
# by stock desc: [('apples', 50), ('oranges', 30), ('bananas', 20)]
Why? Specifying key=lambda kv: kv[1]
tells sorted to compare by the value (stock count).
💡 Bonus Tip: Sorting Custom Objects
# DMask example: custom class
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"{self.name}(${self.price})"
products = [Product("Widget", 25.0), Product("Gadget", 15.5), Product("Doohickey", 22.0)]
by_price = sorted(products, key=lambda p: p.price)
print("sorted products:", by_price)
# output:
# sorted products: [Gadget($15.5), Doohickey($22.0), Widget($25.0)]
Why? You can sort any object by an attribute by passing a key
function.
That’s it! We’ve covered 5 ways to use sorted()
—plus a bonus example with custom classes.
Feel free to mix and match key
and reverse
to fit your data.
Thanks for reading! – BlockDMask
Comments
Post a Comment