How to Sort List of Strings in Python Quickly and Easily
To sort a list of strings in Python, use the
sorted() function or the list's .sort() method. Both arrange strings alphabetically by default, with sorted() returning a new list and .sort() modifying the list in place.Syntax
There are two main ways to sort a list of strings in Python:
sorted(list_of_strings): Returns a new sorted list without changing the original.list_of_strings.sort(): Sorts the list in place, changing the original list.
Both sort alphabetically by default and accept optional parameters like reverse=True to sort in descending order.
python
sorted_list = sorted(list_of_strings)
list_of_strings.sort()Example
This example shows how to sort a list of fruit names alphabetically using both sorted() and .sort().
python
fruits = ['banana', 'apple', 'cherry', 'date'] # Using sorted() returns a new sorted list sorted_fruits = sorted(fruits) print('Sorted with sorted():', sorted_fruits) # Original list remains unchanged print('Original list:', fruits) # Using .sort() sorts the list in place fruits.sort() print('Sorted with .sort():', fruits)
Output
Sorted with sorted(): ['apple', 'banana', 'cherry', 'date']
Original list: ['banana', 'apple', 'cherry', 'date']
Sorted with .sort(): ['apple', 'banana', 'cherry', 'date']
Common Pitfalls
Common mistakes when sorting strings include:
- Expecting
sorted()to change the original list (it does not). - Using
.sort()but forgetting it returnsNone, so assigning its result to a variable will cause errors. - Not considering case sensitivity, which affects sort order (uppercase letters sort before lowercase).
To sort ignoring case, use the key=str.lower parameter.
python
# Wrong: assigning result of .sort() to a variable fruits = ['banana', 'Apple', 'cherry'] sorted_fruits = fruits.sort() # sorted_fruits will be None # Right: use sorted() or call .sort() without assignment sorted_fruits = sorted(fruits, key=str.lower) fruits.sort(key=str.lower) print(sorted_fruits) print(fruits)
Output
['Apple', 'banana', 'cherry']
['Apple', 'banana', 'cherry']
Quick Reference
Summary of sorting list of strings in Python:
| Method | Description | Modifies Original List | Returns Sorted List |
|---|---|---|---|
| sorted(list) | Returns a new sorted list | No | Yes |
| list.sort() | Sorts the list in place | Yes | No (returns None) |
| key=str.lower | Sort ignoring case | Depends on method | Depends on method |
| reverse=True | Sort in descending order | Depends on method | Depends on method |
Key Takeaways
Use
sorted() to get a new sorted list without changing the original.Use
.sort() to sort the list in place; it returns None.To sort strings ignoring case, use the
key=str.lower parameter.Remember that sorting is alphabetical by default and case-sensitive.
Avoid assigning the result of
.sort() to a variable.