Mastering Sorting in Python: Demystifying sort() and sorted() for Different Iterables

--

Sorting is a fundamental operation in programming, and Python offers two main methods for sorting: sort() and sorted(). While both methods achieve the same result—sorting elements—they have distinct behaviors and use cases. In this article, we'll delve into the nuances of these methods, explore their differences, and provide practical examples to help you understand when to use each one effectively.

Overview of sort() and sorted():

sort():

  • Available for lists.
  • Sorts the list in place, modifying the original list.
  • Returns None.

sorted():

  • Built-in function applicable to any iterable.
  • Returns a new sorted list, leaving the original iterable unchanged.

Sorting Lists with sort() and sorted():

my_list = [3, 1, 4, 1, 5, 9, 2]
# Using sort() method
my_list.sort()
print("Using sort():", my_list) # Output: [1, 1, 2, 3, 4, 5, 9]
# Using sorted() function
sorted_list = sorted(my_list)
print("Using sorted():", sorted_list) # Output: [1, 1, 2, 3, 4, 5, 9]

Sorting Tuples with sorted():

my_tuple = (3, 1, 4, 1, 5, 9, 2)

# Using sorted() function
sorted_tuple = tuple(sorted(my_tuple))
print("Sorted tuple:", sorted_tuple) # Output: (1, 1, 2, 3, 4, 5, 9)

Sorting Sets with sorted():

my_set = {3, 1, 4, 1, 5, 9, 2}

# Using sorted() function
sorted_set = sorted(my_set)
print("Sorted set:", sorted_set) # Output: [1, 2, 3, 4, 5, 9]

Sorting Dictionaries by Keys with sorted():

my_dict = {'c': 3, 'a': 1, 'b': 2}

# Using sorted() function to sort by keys
sorted_dict_keys = dict(sorted(my_dict.items()))
print("Sorted dictionary by keys:", sorted_dict_keys) # Output: {'a': 1, 'b': 2, 'c': 3}

Sorting Dictionaries by Values with sorted():

my_dict = {'c': 3, 'a': 1, 'b': 2}

# Using sorted() function to sort by values
sorted_dict_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print("Sorted dictionary by values:", sorted_dict_values) # Output: {'a': 1, 'b': 2, 'c': 3}

Sort the nested dictionaries by their values:

# Define the dictionary
my_dict = {
'dict1': {'a': 4, 'b': 2, 'c': 6},
'dict2': {'x': 1, 'y': 5, 'z': 3}
}

# Print the original dictionary
print("Original dictionary:", my_dict)

# Sort the nested dictionaries by values
for key, val in my_dict.items():
my_dict[key] = dict(sorted(val.items(), key=lambda item: item[1]))

# Print the modified dictionary
print("Modified dictionary:", my_dict)

Sort the lists within each nested dictionary:

# Define the dictionary
my_dict = {
'dict1': {'a': [4, 2], 'b': [2, 1], 'c': [6, 5]},
'dict2': {'x': [1], 'y': [1, 2, 8, 5], 'z': [3, 0]}
}

# Print the original dictionary
print("Original dictionary:", my_dict)

# Sort the nested lists within dictionaries
for key, val in my_dict.items():
my_dict[key] = {i: sorted(j) for i, j in val.items()}

# Print the modified dictionary
print("Modified dictionary:", my_dict)

Performance and Time Complexity:

  • Both sort() and sorted() use the Timsort algorithm, which achieves O(nlogn) time complexity in most cases.

Thanks for learning!

--

--

Smriti Changulani
Python Data Wrangling by Smriti Changulani

Past — Software Engineer. Present — Data Analyst. Future — Data Scientist