Sorting Lists

Sorting lists in Python can be done in two main ways: using the sort() method for in-place sorting or the sorted() function for creating a sorted copy of the list. Both options allow for efficient and flexible sorting with customization options.

Sorting with sort()

The sort() method sorts a list in-place, meaning it rearranges the elements within the original list and does not return a new list. This method only works on lists and modifies them directly.

Syntax:

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

Parameters:

  • reverse: A boolean value. If set to True, the list is sorted in descending order; otherwise, it’s sorted in ascending order (the default).
  • key: A function that acts as a sorting key, often used to sort by specific attributes or customized sorting logic.

Example:

numbers = [5, 2, 9, 1]
numbers.sort()  # Sorts in ascending order
print(numbers)  # Output: [1, 2, 5, 9]

# Sort in descending order
numbers.sort(reverse=True)
print(numbers)  # Output: [9, 5, 2, 1]

Using the key Parameter:

The key parameter allows for complex sorting, such as sorting by the length of strings or by an attribute in a list of objects.

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

Sorting with sorted()

The sorted() function returns a new sorted list and leaves the original list unmodified, which can be beneficial when you need to maintain the original order.

Syntax:

sorted(iterable, reverse=False, key=None)

Parameters:

  • iterable: Any iterable, not just lists (e.g., tuples, dictionaries, etc.).
  • reverse and key parameters function the same as in sort().

Example:

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

Sorting Dictionaries by Values:

dict_values = {'a': 3, 'b': 1, 'c': 2}
sorted_by_value = sorted(dict_values.items(), key=lambda item: item[1])
print(sorted_by_value)  # Output: [('b', 1), ('c', 2), ('a', 3)]

Key Differences Between sort() and sorted():

  • sort() modifies the list in-place and only works with lists.
  • sorted() works with any iterable and returns a new sorted list.