Python list sorting methods

Question

Answers ( 1 )

    0
    2024-01-25T21:33:44+00:00

    It is about how to sort lists in Python, a popular programming language.

    There are several ways to sort lists in Python:

    1. Using the sort() method: This method sorts the list in place, meaning it modifies the original list. It's suitable for when you don't need to keep the original order of the list.

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

      To sort in descending order, use the reverse=True argument:

      numbers.sort(reverse=True)
      print(numbers)  # Output: [9, 5, 4, 3, 2, 1, 1]
      
    2. Using the sorted() function: This function returns a new list that is sorted, leaving the original list unchanged. It's useful when you need to retain the original list order.

      numbers = [3, 1, 4, 1, 5, 9, 2]
      sorted_numbers = sorted(numbers)
      print(sorted_numbers)  # Output: [1, 1, 2, 3, 4, 5, 9]
      

      Similarly, for descending order, use sorted(numbers, reverse=True).

    3. Sorting with a key function: Both sort() and sorted() can take a key parameter, which is a function that specifies a custom way to determine the sorting order.

      For example, to sort a list of strings by their length:

      words = ['apple', 'pear', 'banana']
      words.sort(key=len)
      print(words)  # Output: ['pear', 'apple', 'banana']
      
    4. Sorting by multiple criteria: You can sort by multiple criteria by passing a tuple as the key.

      For example, if you have a list of tuples representing (age, name), and you want to sort primarily by age and then by name:

      people = [(30, 'Alice'), (25, 'Bob'), (30, 'Ann')]
      people.sort(key=lambda person: (person[0], person[1]))
      print(people)  # Output: [(25, 'Bob'), (30, 'Alice'), (30, 'Ann')]
      

    These methods cover most sorting needs in Python. Remember, sort() changes the list in place and is more memory efficient for large lists, while sorted() creates a new sorted list. The key parameter offers powerful customization for sorting logic.

Leave an answer