โ“ Python How-To Guides
Estimated reading: 3 minutes 33 views

๐Ÿ”ƒ Python Sort a List โ€“ Ascending, Descending, Custom Key

๐Ÿงฒ Introduction โ€“ Why Learn List Sorting?

Sorting is a fundamental operation in Python programming. Whether you need to sort:

  • ๐Ÿ”ข Numbers
  • ๐Ÿ…ฐ๏ธ Strings
  • ๐Ÿงฑ Tuples or objects
  • ๐Ÿงช Custom conditions

Python provides powerful and flexible sorting tools using .sort() and sorted().

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to sort a list in Python (ascending and descending)
  • Difference between sort() and sorted()
  • Sort strings, tuples, dictionaries, and objects
  • Use custom key functions for advanced sorting
  • Best practices for clean, reliable code

โœ… 1. Sort a List of Numbers โ€“ Ascending

nums = [5, 2, 9, 1]
nums.sort()
print(nums)  # [1, 2, 5, 9]

โœ… list.sort() sorts the list in place.


๐Ÿ”„ 2. Sort a List of Numbers โ€“ Descending

nums = [5, 2, 9, 1]
nums.sort(reverse=True)
print(nums)  # [9, 5, 2, 1]

โœ… Add reverse=True to flip the order.


๐Ÿ“ค 3. Use sorted() โ€“ Returns a New List

nums = [5, 2, 9, 1]
new_nums = sorted(nums)
print(new_nums)   # [1, 2, 5, 9]
print(nums)       # Original remains unchanged

โœ… Use sorted() when you donโ€™t want to modify the original list.


๐Ÿง  4. Sort Strings Alphabetically

words = ["banana", "apple", "cherry"]
words.sort()
print(words)  # ['apple', 'banana', 'cherry']

๐Ÿ”  Case-Insensitive Sort

words = ["Banana", "apple", "Cherry"]
words.sort(key=str.lower)
print(words)  # ['apple', 'Banana', 'Cherry']

โœ… Use key=str.lower to ignore case sensitivity.


๐Ÿงฎ 5. Sort by Length of Words

words = ["a", "apple", "banana"]
words.sort(key=len)
print(words)  # ['a', 'apple', 'banana']

โœ… Pass any function to key for custom sort criteria.


๐Ÿงฑ 6. Sort a List of Tuples by Second Value

items = [(1, 'b'), (3, 'a'), (2, 'c')]
items.sort(key=lambda x: x[1])
print(items)  # [(3, 'a'), (1, 'b'), (2, 'c')]

โœ… Use lambda functions for advanced sorting logic.


๐Ÿงฐ 7. Sort List of Dictionaries by a Key

people = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
people.sort(key=lambda x: x["age"])
print(people)  # [{'name': 'Bob', ...}, {'name': 'Alice', ...}]

โœ… Sort complex structures like JSON or database records.


๐Ÿ—๏ธ 8. Sort Custom Objects with attrgetter

from operator import attrgetter

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [Person("Alice", 30), Person("Bob", 25)]
people.sort(key=attrgetter("age"))

for p in people:
    print(p.name, p.age)

โœ… Cleaner and faster than lambda x: x.attr.


๐Ÿงช 9. Stable Sort โ€“ Order is Preserved for Equal Items

data = [(2, 'a'), (1, 'b'), (1, 'c')]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)  # [(1, 'b'), (1, 'c'), (2, 'a')]

โœ… Python uses Timsort โ€“ a stable sorting algorithm.


๐Ÿ“˜ Best Practices

โœ… Do ThisโŒ Avoid This
Use .sort() to sort in-placeExpecting .sort() to return a new list
Use sorted() for non-destructive sortOverwriting original list unnecessarily
Use key with lambda or functionsUsing nested loops for sorting
Use attrgetter for object attributesWriting long lambda chains unnecessarily

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Python makes sorting intuitive and powerful. You can sort numbers, strings, tuples, dictionaries, and objects with ease using sort() and sorted().

๐Ÿ” Key Takeaways:

  • โœ… Use .sort() for in-place sorting
  • โœ… Use sorted() to get a new list
  • โœ… Use key functions to customize sorting
  • โœ… Use reverse=True for descending order
  • โœ… Pythonโ€™s sort is stable and fast (Timsort)

โš™๏ธ Real-World Relevance:
Used in data processing, search filters, leaderboards, sorting records, and ranking systems.


โ“ FAQ โ€“ Python Sort a List

โ“ What is the difference between sort() and sorted()?

  • sort() changes the original list
  • sorted() returns a new sorted list

โ“ How do I sort in descending order?

โœ… Use reverse=True:

sorted(data, reverse=True)

โ“ Can I sort by multiple keys?

โœ… Yes, use a tuple in key:

data.sort(key=lambda x: (x[0], x[1]))

โ“ Does sorting change the original list?

  • sort() โ€“ โœ… Yes
  • sorted() โ€“ โŒ No (non-destructive)

โ“ Can I sort a list of dictionaries?

โœ… Yes, using key=lambda x: x["field"]


Share Now :

Leave a Reply

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

Share

Python Sort a List

Or Copy Link

CONTENTS
Scroll to Top