Saturday, January 4, 2025

sort in python

 

The sort() method in Python is used to sort a list in place, meaning the list itself is modified and reordered. It can sort the list in ascending or descending order based on the values or a custom key function.


Syntax:

list.sort(key=None, reverse=False)

Parameters:

  1. key (optional):
    • A function that specifies a sorting criterion. By default, elements are sorted based on their natural order.
    • Example: key=len sorts the list by the length of each element.
  2. reverse (optional):
    • If True, the list is sorted in descending order. Default is False (ascending order).

Examples:

1. Basic Sorting (Ascending Order):

numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers)  # Output: [1, 1, 3, 4, 5, 9]

2. Sorting in Descending Order:

numbers.sort(reverse=True)
print(numbers)  # Output: [9, 5, 4, 3, 1, 1]

3. Custom Sorting Using key:

# Sort strings by their length
words = ["apple", "banana", "cherry", "date"]
words.sort(key=len)
print(words)  # Output: ['date', 'apple', 'banana', 'cherry']

4. Sorting with a Custom Function:

# Sort numbers by their distance from 5
numbers = [10, 2, 8, 3, 6]
numbers.sort(key=lambda x: abs(x - 5))
print(numbers)  # Output: [6, 3, 8, 2, 10]

Key Points:

  1. In-place Sorting:

    • sort() modifies the original list.
    • If you need a new sorted list without changing the original, use the sorted() function instead.
    original = [3, 1, 4]
    sorted_list = sorted(original)  # New sorted list
    print(original)  # Output: [3, 1, 4]
    
  2. Non-comparable Elements:

    • Sorting a list with incompatible types (e.g., numbers and strings) will raise a TypeError.
  3. Efficient Sorting:

    • sort() uses the Timsort algorithm, which is highly optimized and stable.

The sort() method is ideal for in-place sorting, while sorted() is more versatile for generating new sorted lists.

No comments:

Post a Comment