sorted()Intermediate Examples

Returns a new sorted list from any iterable

sorted() with keyword arguments

Using sorted() with optional parameters and in iteration patterns.

python
# sorted() with key function
words = ["banana", "Apple", "cherry", "date"]
print(sorted(words))
print(sorted(words, key=str.lower))
print(sorted(words, key=len))

# Sort complex objects
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
print(sorted(people, key=lambda p: p[1]))

sorted() supports additional parameters that modify its behavior.

sorted() in real-world code

Practical patterns using sorted().

python
# Common sorted() patterns in production code
print("sorted() is frequently used for data transformation")

# Example: processing a list
data = [1, 2, 3, 4, 5]
print(f"Sum: {sum(data)}")
print(f"Max: {max(data)}")
print(f"Sorted: {sorted(data, reverse=True)}")

These patterns show how sorted() is commonly used in production code.

Want to try these examples interactively?

Open Intermediate Playground