Python

Python sorted() Function

The sorted() function is used to sort the elements of an iterable and return a new sorted list.

It can sort:

  • Numbers
  • Strings
  • Lists
  • Tuples
  • Dictionaries
  • Objects and complex data
  • Data using custom sorting rules

Basic Syntax

sorted(iterable, key=None, reverse=False)

Parameters

ParameterDescription
iterableThe data you want to sort
keyOptional function used to determine the sorting value
reverseFalse for ascending, True for descending

1. Basic Example

numbers = [5, 2, 8, 1, 3]

result = sorted(numbers)

print(result)

Output:

[1, 2, 3, 5, 8]

The original list is not changed.

2. Ascending Order

By default, sorted() sorts in ascending order.

numbers = [50, 10, 40, 20, 30]

print(sorted(numbers))

Output:

[10, 20, 30, 40, 50]

3. Descending Order

Use:

reverse=True

Example:

numbers = [50, 10, 40, 20, 30]

result = sorted(
    numbers,
    reverse=True
)

print(result)

Output:

[50, 40, 30, 20, 10]

4. Sorting Strings

names = ["Ram", "Sita", "Hari", "Gita"]

result = sorted(names)

print(result)

Output:

['Gita', 'Hari', 'Ram', 'Sita']

Strings are sorted alphabetically based on their character values.

5. Reverse String Sorting

names = ["Ram", "Sita", "Hari", "Gita"]

result = sorted(
    names,
    reverse=True
)

print(result)

Output:

['Sita', 'Ram', 'Hari', 'Gita']

6. sorted() Does Not Modify the Original List

This is an important difference between sorted() and the list .sort() method.

numbers = [5, 2, 8, 1]

result = sorted(numbers)

print("Original:", numbers)
print("Sorted:", result)

Output:

Original: [5, 2, 8, 1]
Sorted: [1, 2, 5, 8]

The original list remains unchanged.

7. sort() vs sorted()

sort()

numbers = [5, 2, 8, 1]

numbers.sort()

print(numbers)

The original list is modified.

sorted()

numbers = [5, 2, 8, 1]

result = sorted(numbers)

print(numbers)
print(result)

The original list remains unchanged.

Main difference

list.sort()
    ↓
Changes the original list

sorted()
    ↓
Returns a new sorted list

8. Sort a Tuple

sorted() can sort a tuple.

numbers = (5, 2, 8, 1, 3)

result = sorted(numbers)

print(result)

Output:

[1, 2, 3, 5, 8]

Notice that the result is a list, not a tuple.

9. Sort a Set

numbers = {5, 2, 8, 1, 3}

result = sorted(numbers)

print(result)

Output:

[1, 2, 3, 5, 8]

Again, the result is a list.

10. Sort a String

A string is iterable, so sorted() can sort its characters.

word = "python"

result = sorted(word)

print(result)

Output:

['h', 'n', 'o', 'p', 't', 'y']

If you want the result back as a string:

word = "python"

result = "".join(
    sorted(word)
)

print(result)

Output:

hnopty

11. Sort by String Length

The key parameter allows you to specify how the values should be sorted.

names = ["Rajendra", "Ram", "Sita", "Hari"]

result = sorted(
    names,
    key=len
)

print(result)

Output:

['Ram', 'Sita', 'Hari', 'Rajendra']

Here:

key=len

means:

Sort the names according to their length.

12. Sort by Length in Descending Order

names = ["Rajendra", "Ram", "Sita", "Hari"]

result = sorted(
    names,
    key=len,
    reverse=True
)

print(result)

Output:

['Rajendra', 'Sita', 'Hari', 'Ram']

13. Using lambda with key

You can use a lambda function with key.

numbers = [5, 2, 8, 1, 3]

result = sorted(
    numbers,
    key=lambda x: x
)

print(result)

Output:

[1, 2, 3, 5, 8]

Here, the lambda simply returns each number.

14. Sort by Last Character

names = ["Ram", "Sita", "Hari", "Gita"]

result = sorted(
    names,
    key=lambda name: name[-1]
)

print(result)

Output:

['Sita', 'Gita', 'Hari', 'Ram']

The sorting is based on the last character.

15. Sort by First Character

names = ["Ram", "Sita", "Hari", "Gita"]

result = sorted(
    names,
    key=lambda name: name[0]
)

print(result)

Output:

['Gita', 'Hari', 'Ram', 'Sita']

16. Sort Numbers by Their Absolute Value

numbers = [-10, 5, -3, 8, -1]

result = sorted(
    numbers,
    key=abs
)

print(result)

Output:

[-1, -3, 5, 8, -10]

The sorting is based on:

1, 3, 5, 8, 10

rather than the actual negative values.

17. Sort by Even and Odd

You can use a condition as the sorting key.

numbers = [5, 2, 8, 1, 3, 6]

result = sorted(
    numbers,
    key=lambda x: x % 2
)

print(result)

Output:

[2, 8, 6, 5, 1, 3]

Why?

Even → x % 2 = 0
Odd  → x % 2 = 1

So even numbers come first.

18. Sort Students by Marks

Suppose we have:

students = [
    ("Ram", 75),
    ("Sita", 85),
    ("Hari", 65),
    ("Gita", 90)
]

Sort by marks:

result = sorted(
    students,
    key=lambda student: student[1]
)

print(result)

Output:

[
    ('Hari', 65),
    ('Ram', 75),
    ('Sita', 85),
    ('Gita', 90)
]

19. Sort Students by Marks Descending

students = [
    ("Ram", 75),
    ("Sita", 85),
    ("Hari", 65),
    ("Gita", 90)
]

result = sorted(
    students,
    key=lambda student: student[1],
    reverse=True
)

print(result)

Output:

[
    ('Gita', 90),
    ('Sita', 85),
    ('Ram', 75),
    ('Hari', 65)
]

20. Sort Students by Name

students = [
    ("Ram", 75),
    ("Sita", 85),
    ("Hari", 65),
    ("Gita", 90)
]

result = sorted(
    students,
    key=lambda student: student[0]
)

print(result)

Output:

[
    ('Gita', 90),
    ('Hari', 65),
    ('Ram', 75),
    ('Sita', 85)
]

21. Sort Dictionary by Values

Consider:

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 65,
    "Gita": 90
}

We can sort its items by marks:

result = sorted(
    students.items(),
    key=lambda item: item[1]
)

print(result)

Output:

[
    ('Hari', 65),
    ('Ram', 75),
    ('Sita', 85),
    ('Gita', 90)
]

22. Sort Dictionary by Values Descending

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 65,
    "Gita": 90
}

result = sorted(
    students.items(),
    key=lambda item: item[1],
    reverse=True
)

print(result)

Output:

[
    ('Gita', 90),
    ('Sita', 85),
    ('Ram', 75),
    ('Hari', 65)
]

23. Sort Dictionary by Keys

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 65,
    "Gita": 90
}

result = sorted(
    students.items(),
    key=lambda item: item[0]
)

print(result)

Output:

[
    ('Gita', 90),
    ('Hari', 65),
    ('Ram', 75),
    ('Sita', 85)
]

24. Sort Dictionary into Another Dictionary

If you want the result as a dictionary:

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 65,
    "Gita": 90
}

result = dict(
    sorted(
        students.items(),
        key=lambda item: item[1]
    )
)

print(result)

Output:

{
    'Hari': 65,
    'Ram': 75,
    'Sita': 85,
    'Gita': 90
}

25. Sort Products by Price

products = [
    ("Laptop", 80000),
    ("Mouse", 1500),
    ("Keyboard", 3000),
    ("Monitor", 25000)
]

result = sorted(
    products,
    key=lambda product: product[1]
)

for product, price in result:
    print(product, price)

Output:

Mouse 1500
Keyboard 3000
Monitor 25000
Laptop 80000

26. Sort Products by Price Descending

result = sorted(
    products,
    key=lambda product: product[1],
    reverse=True
)

for product, price in result:
    print(product, price)

Output:

Laptop 80000
Monitor 25000
Keyboard 3000
Mouse 1500

27. Sort List of Dictionaries

This is very common when working with APIs and databases.

students = [
    {"name": "Ram", "marks": 75},
    {"name": "Sita", "marks": 85},
    {"name": "Hari", "marks": 65},
    {"name": "Gita", "marks": 90}
]

result = sorted(
    students,
    key=lambda student: student["marks"]
)

for student in result:
    print(student)

Output:

{'name': 'Hari', 'marks': 65}
{'name': 'Ram', 'marks': 75}
{'name': 'Sita', 'marks': 85}
{'name': 'Gita', 'marks': 90}

28. Sort API-Like Data

courses = [
    {"name": "Python", "price": 15000},
    {"name": "Django", "price": 18000},
    {"name": "MERN", "price": 22000},
    {"name": "Data Science", "price": 25000}
]

result = sorted(
    courses,
    key=lambda course: course["price"],
    reverse=True
)

for course in result:
    print(
        course["name"],
        course["price"]
    )

Output:

Data Science 25000
MERN 22000
Django 18000
Python 15000

29. Case-Insensitive Sorting

Normal string sorting can treat uppercase and lowercase differently.

Use:

key=str.lower

Example:

names = ["ram", "Sita", "hari", "Gita"]

result = sorted(
    names,
    key=str.lower
)

print(result)

Output:

['Gita', 'hari', 'ram', 'Sita']

The sorting is performed using lowercase versions.

30. Sort by Multiple Criteria

You can return a tuple from the key function.

Example:

students = [
    ("Ram", 75),
    ("Sita", 85),
    ("Hari", 75),
    ("Gita", 90)
]

result = sorted(
    students,
    key=lambda student: (student[1], student[0])
)

print(result)

Output:

[
    ('Hari', 75),
    ('Ram', 75),
    ('Sita', 85),
    ('Gita', 90)
]

First, it sorts by marks.

If marks are equal, it sorts by name.

31. Multiple Criteria with Dictionaries

students = [
    {"name": "Ram", "marks": 75},
    {"name": "Sita", "marks": 85},
    {"name": "Hari", "marks": 75},
    {"name": "Gita", "marks": 90}
]

result = sorted(
    students,
    key=lambda student: (
        student["marks"],
        student["name"]
    )
)

for student in result:
    print(student)

Output:

{'name': 'Hari', 'marks': 75}
{'name': 'Ram', 'marks': 75}
{'name': 'Sita', 'marks': 85}
{'name': 'Gita', 'marks': 90}

32. Sort by Length Then Alphabetically

words = [
    "cat",
    "apple",
    "dog",
    "banana",
    "car"
]

result = sorted(
    words,
    key=lambda word: (len(word), word)
)

print(result)

Output:

['car', 'cat', 'dog', 'apple', 'banana']

First sorting happens by length.

If lengths are equal, alphabetical sorting is applied.

33. sorted() with filter()

You can combine the functions you've already learned.

numbers = [10, 25, 40, 15, 30, 5]

filtered = filter(
    lambda x: x >= 20,
    numbers
)

result = sorted(filtered)

print(result)

Output:

[25, 30, 40]

First:

filter()
   ↓
25, 40, 30

Then:

sorted()
   ↓
25, 30, 40

34. sorted() with map()

You can also combine map() and sorted().

numbers = [5, 2, 8, 1]

result = sorted(
    map(lambda x: x * 2, numbers)
)

print(result)

Output:

[2, 4, 10, 16]

First map() transforms the values:

5 → 10
2 → 4
8 → 16
1 → 2

Then sorted() sorts them.

35. sorted() with Generator Expression

You can combine sorted() with the previous topic.

numbers = [5, 2, 8, 1, 3]

result = sorted(
    x ** 2
    for x in numbers
)

print(result)

Output:

[1, 4, 9, 25, 64]

36. sorted() with enumerate()

You can also sort enumerated values.

names = ["Ram", "Sita", "Hari", "Gita"]

result = sorted(
    enumerate(names),
    key=lambda item: item[1]
)

print(result)

Output:

[
    (3, 'Gita'),
    (2, 'Hari'),
    (0, 'Ram'),
    (1, 'Sita')
]

Here each item is:

(index, value)

37. Practical Example : Rank Students

students = [
    {"name": "Ram", "marks": 75},
    {"name": "Sita", "marks": 85},
    {"name": "Hari", "marks": 65},
    {"name": "Gita", "marks": 90}
]

ranking = sorted(
    students,
    key=lambda student: student["marks"],
    reverse=True
)

for rank, student in enumerate(ranking, start=1):
    print(
        rank,
        student["name"],
        student["marks"]
    )

Output:

1 Gita 90
2 Sita 85
3 Ram 75
4 Hari 65

This combines:

sorted()
enumerate()
lambda
dictionary

38. Practical Example : Course Ranking

courses = [
    {"name": "Python", "students": 120},
    {"name": "Django", "students": 80},
    {"name": "MERN", "students": 150},
    {"name": "Data Science", "students": 100}
]

ranking = sorted(
    courses,
    key=lambda course: course["students"],
    reverse=True
)

for rank, course in enumerate(ranking, start=1):
    print(
        rank,
        course["name"],
        course["students"]
    )

Output:

1 MERN 150
2 Python 120
3 Data Science 100
4 Django 80

39. Important key Concept

The key parameter does not change the values being sorted.

It tells Python which value to use for comparison.

Example:

names = ["Rajendra", "Ram", "Sita"]

result = sorted(
    names,
    key=len
)

Python effectively compares:

Rajendra → 8
Ram      → 3
Sita     → 4

So the result becomes:

['Ram', 'Sita', 'Rajendra']

The actual strings remain unchanged.

40. Important Points to Remember

Basic sorting

sorted(numbers)

Descending

sorted(
    numbers,
    reverse=True
)

Sort using a key

sorted(
    names,
    key=len
)

Sort using lambda

sorted(
    students,
    key=lambda student: student[1]
)

Sort dictionaries

sorted(
    students.items(),
    key=lambda item: item[1]
)

Main difference

sorted()
   ↓
Returns a NEW sorted list

list.sort()
   ↓
Changes the ORIGINAL list
Interactive Sandbox
Python