Sort Lists
2 min read ·
Sorting lists is a common task in Python when you need to organize data in a specific order.
Python provides powerful and flexible ways to sort lists in-place or by creating a new sorted list.
Sort a List Using sort()
The
sort() method sorts the list in ascending order by default and modifies the original list.Sort in Descending Order
Use the
reverse=True argument.Sort a List Using sorted()
The
sorted() function returns a new sorted list without changing the original.Sort by Length Using key
The
key parameter allows custom sorting logic.Sort List of Tuples
Sort with Case Sensitivity
By default, uppercase letters come first.
Case-Insensitive Sort
Reverse a List Without Sorting
Sort Numeric vs String Values
Sorting Nested Lists
Common Mistakes
Expecting sort() to Return a List
sort() returns None.Mixing Incompatible Types
Performance Note
sort()is faster for large listssorted()is useful when original order must be preserved- Python uses Timsort, which is efficient and stable