sorted and reversed

Sorting and reversing iterables

Interview Relevant: Common operations

sorted and reversed

Sort and reverse sequences.

Code Examples

Sorting and reversing functions.

python
1nums = [3, 1, 4, 1, 5, 9]
2
3# sorted - returns new list
4sorted(nums)              # [1, 1, 3, 4, 5, 9]
5sorted(nums, reverse=True) # [9, 5, 4, 3, 1, 1]
6
7# Custom key function
8words = ["banana", "apple", "cherry"]
9sorted(words, key=len)           # By length
10sorted(words, key=str.lower)     # Case-insensitive
11
12# Complex sorting
13people = [("Alice", 25), ("Bob", 20)]
14sorted(people, key=lambda x: x[1])  # By age
15
16# reversed - returns iterator
17list(reversed(nums))  # [9, 5, 1, 4, 1, 3]
18
19# Stable sort (maintains relative order)
20# Python's sort is stable!

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In