Difference between Sort and Sorted in Python
If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them correctly and effectively. In this article, we will discuss the difference between Sort and Sorted in Python and provide examples of where each should be used. We will also explain how to make sure the data is sorted correctly in each situation and quickly identify which sorting method is best for each type of data. After reading this article, you will have a better understanding of the differences between Sort and Sorted and be better equipped to use both to their full potential in your Python programming.
Sort() in Python
In Python, the built-in sort() method is used to sort a list in ascending order. The sort() method modifies the original list in place and does not return any value. The elements of the list are ordered in ascending order, meaning that the smallest element will be at the beginning of the list and the largest element will be at the end. The sort() method uses the "less than" operator (<) to determine the order of elements in the list.
The sort() method has the following syntax:
list.sort(key=None, reverse=False)
The key parameter is used to specify a function to be called on each list element prior to making comparisons.
The reverse parameter is a Boolean value that determines whether to sort the list in ascending (False) or descending (True) order.
Here is an example of using the sort() method to sort a list of numbers:
Example 1:
numbers = [7, 3, 9, 5]
numbers.sort()
print(numbers)
Output:
[3, 5, 7, 9]
You can also sort a list in descending order by passing the reverse=True argument to the sort() method:
Example 2:
numbers = [7, 3, 9, 5]
numbers.sort(reverse=True)
print(numbers)
Output:
[9, 7, 5, 3]
You can also sort a list of strings or other objects by providing a key argument to the sort() function. For example, here is how you would sort a list of strings by their length:
Example 3:
words = ["cat", "dog", "elephant", "bird"]
words.sort(key=len)
print(words)
Output:
['cat', 'dog', 'bird', 'elephant']
Sorted in Python
Sorted is an inbuilt function in Python that takes a sequence and returns a sorted list containing all the elements of the iterable. It is similar to the sort function, with the only difference being that it returns a sorted list while the former doesn’t.
The syntax of the sorted() function is:
sorted(iterable, key=None, reverse=False)
The parameters of the sorted() function are:
- iterable: This is the sequence that needs to be sorted.
- key: This is the key based on which the sorting will happen.
- reverse: This is an optional parameter, which if set to True, sorts the sequence in descending order.
The sorted() function works on both mutable and immutable objects. It is a function that preserves the original elements and returns a new sorted list.
The sorted() function can take a list, tuple, set, dictionary, etc. as the input argument and returns a sorted list. The sorting is based on the sort order of the values. The dictionary can be sorted in both alphabetical order and numerical order.
Here is an example of using the sorted() function in Python to sort a list of numbers:
Example:
numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
Output:
[1, 2, 3, 4, 5]
You can use the reverse=True parameter to sort the list in descending order:
Example:
numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)
Output:
[5, 4, 3, 2, 1]
You can also use the sorted() function to sort a list of strings:
Example:
words = ['banana', 'apple', 'cherry']
sorted_words = sorted(words)
print(sorted_words)
Output:
['apple', 'banana', 'cherry']
You can also sort a list of tuples and a list of dictionary based on a key
//sorting a list of tuples
Example:
tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')]
sorted_tuples = sorted(tuples, key=lambda x: x[1])
print(sorted_tuples)
Output:
[(4, 'a'), (2, 'b'), (3, 'c'), (1, 'd')]
//sorting a list of dictionary
Example:
dicts = [{'name': 'John', 'age': 25}, {'name': 'Emily', 'age': 22}, {'name': 'Michael', 'age': 40}]
sorted_dicts = sorted(dicts, key=lambda x: x['age'])
print(sorted_dicts)
Output:
[{'name': 'Emily', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Michael', 'age': 40}]
Key Differences between Sort And Sorted
1. Syntax: The syntax for sorting a list using the sort() method is list_name.sort() and the syntax for sorting a list using the sorted() method is sorted(list_name).
2. Modifying the List: The sort() method modifies the original list by sorting it in place, while the sorted() method returns a new sorted list without changing the original one.
3. Parameters: Both sort() and sorted() methods take in one optional parameter - reverse. This is a Boolean parameter that reverses the sorting order if set to True.
4. Performance: The sort() method is faster than the sorted() method as the latter creates a new list and takes up more memory.
5. Stability: The sort() method is stable while the sorted() method is not. This means that the two methods will produce different results when dealing with duplicate values in the list.
6. Return:The sort() method does not return anything. It only sorts the list, whereas the sorted() function returns a new sorted list.
7. Datatypes: The sort() method can only be used to sort lists that contain elements of the same data type, while the sorted() function can be used to sort lists that contain elements of different data types.
Note: It is important to note that depending on the use case and the requirements, one function might be more suitable than the other. Sort is ideal when you have a large list and want to avoid creating a new one and when you want to sort the list in place and keep the original list the same. On the other hand, Sorted is ideal when you want to keep the original list intact or when you're working with a smaller list and memory efficiency is important.
Conclusion:
In conclusion, both Sort and Sorted are powerful functions in Python that provide different ways to sort lists. The choice between them depends on the specific requirements of your application.