Python – Sort Lists

1. What Does “Sort List” Mean?

Sorting a list means arranging items in order.

For example:

  • Numbers → small to big

  • Words → A to Z

Python makes sorting very easy.

2. Sort List Using sort()

sort() arranges the list in ascending order by default.

Example (Numbers)

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

numbers.sort()
print(numbers)

Output:

[1, 2, 3, 5, 9]

Example (Strings)

fruits = ["banana", "apple", "orange"]

fruits.sort()
print(fruits)

Output:

['apple', 'banana', 'orange']

3. Sort List in Descending Order

Use reverse=True.

Example

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

numbers.sort(reverse=True)
print(numbers)

Output:

[9, 5, 3, 2, 1]

4. Sort Without Changing Original List

Use sorted().

Example

numbers = [3, 1, 4, 2]

new_list = sorted(numbers)

print(new_list)
print(numbers)

👉 Original list stays the same.

5. Sort List by Length of Words

Use key.

Example

words = ["apple", "kiwi", "banana"]

words.sort(key=len)
print(words)

Output:

['kiwi', 'apple', 'banana']

6. Sort List Case-Insensitive

Example

names = ["banana", "Apple", "cherry"]

names.sort(key=str.lower)
print(names)

7. Sort Numbers and Strings (Common Mistake)

❌ Wrong

data = [10, "apple", 5]
data.sort()

❌ Error: cannot compare number and text.

8. Common Beginner Mistakes

❌ Expecting sort() to return list

new_list = numbers.sort()

✔ Correct:

numbers.sort()

❌ Forgetting reverse=True

numbers.sort(False)

✔ Correct:

numbers.sort(reverse=True)

9. Simple Practice Examples

Example 1: Sort Marks

marks = [88, 45, 70, 90]

marks.sort()
print(marks)

Example 2: Sort Cities A–Z

cities = ["Delhi", "Mumbai", "Chennai"]

cities.sort()
print(cities)

Example 3: Sort by Length

colors = ["red", "blue", "green"]

colors.sort(key=len)
print(colors)

10. Summary (Sort Lists)

sort() changes original list
sorted() keeps original list
✔ Use reverse=True for descending
✔ Use key for custom sorting
✔ Sorting is very useful

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Copy Lists

  • Join Lists

  • Tuple Basics

  • Set Basics

  • List Exercises

Just tell me 😊

You may also like...