Python Sort Lists – The Ultimate Guide to Sorting in Python

python sort lists

Sorting is something that most programmers do almost every day (could be every day depending on what you do. Sorting is part of any programming you do such as sorting exam scores, sorting products by price, cleaning data, etc. Sorting is ubiquitous.

Python Sort Lists is super simple and really powerful. You don’t need to create anything because Python gives you tools that can do sorting for simple lists of numbers all the way to sorting with lots of custom logic with sort() and sorted().

python sort lists
Python Sort Lists

In this guide we will cover everything you need to know about python sort list: the difference between sort() and sorted(), sorting numbers, strings, tuples, dictionaries, custom sorting and a lambda function. By the end of this guide you will be able to tackle whatever python sorting list techniques you need.

🔑 Python Sort Lists Basics: sort() vs sorted()

sorting list python
Python Sort Lists Basics: sort() vs sorted()

When it comes to sorting a list in Python you have two options:

  1. sort() – This method sorts the list in place, meaning it modifies the original list and does not return a copy.
  2. sorted(list) – This returns a new sorted list and maintains the original list.

👉 Example:

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

# Using sort()

numbers.sort()

print("Using sort():", numbers)  # [1, 2, 5, 7, 9]

 # Using sorted()numbers = [5, 2, 9, 1, 7]

new_list = sorted(numbers)

print("Using sorted():", new_list)  # [1, 2, 5, 7, 9]

print("Original list:", numbers)    # [5, 2, 9, 1, 7]

👉 Use sort() when you don’t need the original order.
👉 Use sorted() when you want to preserve the original list.

🔢 Sorting Numbers in Python

If you’re working with integers or floats, list python sort is straightforward.

nums = [10, 3, 8, 2, 7]

nums.sort()

print(nums)  # [2, 3, 7, 8, 10]

To sort in descending order, just add reverse=True:

nums = [10, 3, 8, 2, 7]

nums.sort(reverse=True)

print(nums)  # [10, 8, 7, 3, 2]

🔤 Sorting Strings in Python

Sorting strings works alphabetically (lexicographically).

words = ["banana", "apple", "cherry", "date"]

words.sort()

print(words)  # ['apple', 'banana', 'cherry', 'date']

Sorting in reverse (Z → A):

words.sort(reverse=True)

print(words)  # ['date', 'cherry', 'banana', 'apple']

🛠 Sorting with Key Parameter

The real power of sorting list python comes with the key parameter. It lets you define how the list should be sorted.

Example: Sort by Length of Words

words = ["banana", "apple", "cherry", "date"]

words.sort(key=len)

print(words)  # ['date', 'apple', 'banana', 'cherry']

Example: Case-Insensitive Sorting

words = ["Banana", "apple", "Cherry", "date"]

words.sort(key=str.lower)

print(words)  # ['apple', 'Banana', 'Cherry', 'date']

🧑‍💻 Sorting with Lambda Functions

Sometimes you need custom logic. Enter lambda functions.

Example: Sort by Last Character

words = ["banana", "apple", "cherry", "date"]

words.sort(key=lambda x: x[-1])

print(words)  # ['banana', 'apple', 'date', 'cherry']

📂 Sorting a List of Tuples

Lists of tuples are common in Python (like datasets).

students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)] 

# Sort by marksstudents.sort(key=lambda x: x[1])

print(students)  # [('Charlie', 78), ('Alice', 85), ('Bob', 92)]

📑 Sorting a List of Dictionaries

If you’ve ever handled JSON data, you’ll know how useful this is.

people = [    {"name": "Alice", "age": 25},    {"name": "Bob", "age": 20},    {"name": "Charlie", "age": 30}] 

# Sort by age

sorted_people = sorted(people, key=lambda x: x["age"])

print(sorted_people)

Output:

[{‘name’: ‘Bob’, ‘age’: 20}, {‘name’: ‘Alice’, ‘age’: 25}, {‘name’: ‘Charlie’, ‘age’: 30}]

⚡ Performance of Python List Sorting

Python uses Time sort for sorting lists, which has:

  • O(n log n) average and worst-case time complexity.
  • Optimized for real-world data, making it one of the fastest sorting algorithms.

🌍 Real-World Examples of Sorting in Python

python sort lists
Real-World Examples of Sorting in Python

Applying sorting algorithms:

  • E-Commerce: Sort a product’s price, rating, or popularity.
  • Education: Sort students by marks or GPA.
  • Data Science: Sort data-sets before processing.
  • Games: Sort a leader-board by score.

👉 Example: Sorting Student Grades

grades = [88, 92, 74, 63, 95, 82]

grades.sort(reverse=True)

print("Top scores:", grades[:3])  # [95, 92, 88]

⚔️ Python sort() vs sorted(): Which One to Use?

Python’s sorting algorithm is Time sort and it has:·

  • O(n log n) average and worst-case time complexity.·
  • Optimized performance on real-world data resulting in being one of the fastest sorting algorithms.
 tuple_data = (3, 1, 4)

print(sorted(tuple_data))  # [1, 3, 4]

FAQs on Python Sort Lists

Q1: Can you sort a list in Python without changing it?
Yes, use sorted(list) instead of list.sort().

Q2: How to sort list python in descending order?
Use list.sort(reverse=True) or sorted(list, reverse=True).

Q3: What’s the difference between sort and sorted in Python?
sort() modifies the list, sorted() returns a new one.

Q4: Can I sort complex objects in Python?
Yes, use the key parameter with lambda or custom functions.

Conclusion

Sorting is one of the most important skills in Python programming, whether you’re using numbers, strings, tuples, or dictionaries, Python has all the functionality, from sort() to sorted(). Once you understand how to wield the key parameter skillfully, paired with lambda functions, you’re able to sort lists in Python in virtually any way you can think of.

The next time you’re faced with data or project work, keep these techniques in mind to keep your sorting lists python tasks efficient and clean.

Related Reads

Previous Article

How to Read RAM Contents: A Practical Guide to RAM Analysis and RAM Dump

Next Article

IT Jobs 2025 – Software Development Engineer at Nokia Bangalore 🚀

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨