Tuesday, January 14, 2025
HomeTechPython List sort() Method

Python List sort() Method

The sort() method in Python is used to sort the elements of a list in a specific order, either ascending (default) or descending. It sorts the list in place, meaning it modifies the original list and does not return a new list.

Syntax

list.sort(key=None, reverse=False)
  • key (optional): A function that serves as a basis for sorting. Default is None, which means the elements are sorted directly.
  • reverse (optional): A boolean. If True, the list is sorted in descending order. Default is False.

Examples

1. Sorting a List in Ascending Order (Default Behavior)

numbers = [4, 1, 7, 3]
numbers.sort()
print(numbers)

Output:

[1, 3, 4, 7]

2. Sorting a List in Descending Order

numbers = [4, 1, 7, 3]
numbers.sort(reverse=True)
print(numbers)

Output:

[7, 4, 3, 1]

3. Using the key Parameter

The key parameter lets you define a custom sorting function.

  • Sort by Absolute Values:
numbers = [-10, 5, -2, 3]
numbers.sort(key=abs)
print(numbers)

Output:

[-2, 3, 5, -10]
  • Sort by String Length:
words = ["banana", "apple", "kiwi", "cherry"]
words.sort(key=len)
print(words)

Output:

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

4. Sorting Strings Alphabetically

fruits = ['banana', 'apple', 'cherry']
fruits.sort()
print(fruits)

Output:

['apple', 'banana', 'cherry']

5. Sorting Strings in Reverse Alphabetical Order

fruits = ['banana', 'apple', 'cherry']
fruits.sort(reverse=True)
print(fruits)

Output:

['cherry', 'banana', 'apple']

6. Case-Insensitive Sorting

To sort strings ignoring case, use str.lower with the key parameter.

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

Output:

['apple', 'Banana', 'Cherry']

Important Notes

  1. Modifies the Original List:
    • The sort() method does not return a new list; it modifies the original list in place.
    • To create a sorted copy, use the sorted() function instead.
  2. Only Works on Lists:
    • The sort() method is a list-specific method. Other iterables like tuples or sets do not support it. Use sorted() for such cases.
  3. Stable Sorting:
    • Python’s sort() is stable, meaning the relative order of equal elements is preserved.
See also  How to Forward Calls on Android

Using sorted() Instead of sort()

If you need a new sorted list without modifying the original:

numbers = [4, 1, 7, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 3, 4, 7]
print(numbers)         # Original list remains unchanged

The sort() method is a powerful tool for in-place list sorting, with flexibility for custom sorting through its key and reverse parameters.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x