Get a skill gap analysis, personalised roadmap, and AI-powered resume optimisation.
Introduction
Sorting is a fundamental operation in programming, and Python provides two built-in tools to handle it: the sort() method and the sorted() function. While they achieve similar outcomes, their usage, behavior, and return types differ significantly. In this blog, we’ll explore the key differences between sort() and sorted() in Python.
Let's explore the difference between sort and sorted functions in Python together!
Differences Between Sort and Sorted in Python
The following table summarizes the key differences between sort and sorted functions in Python:
Feature
sort()
sorted()
Behaviour
In-place sort.
Returns a new sorted list.
Original list
Modified
Unmodified
Performance
Faster for large lists.
Slower for large lists.
Reversing
No direct method, but you can use reverse=True with sort().
Can use reverse=True with sorted().
Key Error
It will give an error if the key is not present.
Only give KeyError if the key is present.
Multiple Keys
It cannot sort by multiple.
It can sort by multiple keys using the key parameter.
Sorting Order
Only sorts in ascending order.
You can sort in ascending or descending order using the reverse parameter.
Sorting in Python
Sorting in Python is a way to arrange things in a specific order. You can organize the data in ascending or descending order according to your need. Sorting is very helpful when finding particular items in your data. There are two ways to sort your data using a built-in function in Python:
sort() function
sorted() function.
Here is an example of sorting a list of numbers in ascending order.
CODE
Python
Python
numbers = [3, 6, 1, 8, 2, 9, 5] sorted_numbers = [] while numbers: minimum = numbers[0] # Set the first element as the current minimum for x in numbers: #If any element is smaller than the current minimum, then update the minimum if x < minimum: minimum = x # Add minimum to the sorted_numbers list sorted_numbers.append(minimum) # remove minimum from the numbers list numbers.remove(minimum) print(sorted_numbers)
You can also try this code with Online Python Compiler
In this example, the list numbers are sorted by finding the minimum value in the list and appending it to a new list sorted_numbers until no more values are left in the numbers. The remove() method removes the minimum value from numbers after it has been added to sorted_numbers.
The most efficient way to sort a list in Python is by using built-in sorting functions such as Sorted or Sort.
Sort() Function in Python
The sort() method in Python can sort a list of elements in a specific order. By default, this function sorts elements in ascending order. You can also use parameters to sort items in a different order according to your requirements, like from largest to smallest. The sort() function modifies the existing input list and does not return a new one.
The sort() function compares the first two elements of the list and swaps them if they are not in order. It then compares the next element with the first element, switches them if necessary, and moves on to the next element until the entire input list is sorted.
Syntax
list_name.sort(reverse=False, key=None)
Here are some examples of using the sort() function in Python:
Example 1: Sorting a list of integers in ascending order
Call sort() on the list of integers and the list will be sorted in place.
The sorted list will be in ascending order. If you want to sort the list in descending order, pass the reverse=True argument.
Example 3: Sorting a list of tuples based on the second element
Use a lambda function as the key parameter, using each tuple's second element as the sorting criterion. Based on the second element of each tuple, the sorted output list will be printed in ascending order.
Example 4: Sorting a list of custom objects based on a specific property
Use a lambda function as the key parameter, with the specific property of the custom object as the sorting criteria. Based on the particular property of the custom object, the sorted output list will be printed in ascending order.
CODE
Python
Python
class Student: def __init__(self, name, marks): self.name = name self.marks = marks def __repr__(self): return f"{self.name}: {self.marks}" students = [Student('Ram', 80), Student('Shyam', 90), Student('Sita', 75), Student('Gita', 85)] def get_marks(student): return student.marks students.sort(key=get_marks) print(students)
You can also try this code with Online Python Compiler
O(nlog(n)) : The time complexity of sort() function in Python is O(n log n) on average, and in the worst case, where n is the number of elements in the list to be sorted. This is because sort() use the timsort algorithm, which has this time complexity.
Space Complexity
O(n) : The sort() method only uses additional space when performing a timsort, and in the worst case, it requires O(n) space, where n is the number of elements in the list.
Sorted() Function in Python
The sorted function is used to sort a list of elements in ascending or descending order. It takes an iterable object (a list or tuple) as input and returns a new sorted list. By default, the sorted function sorts elements in ascending order, but you can specify the reverse=True argument to sort in descending order according to your need. Be careful when sorting vast input, as very long lists can be relatively slow.
Syntax
sorted(iterable, key=None, reverse=False)
Here are some examples of using the sorted() function in Python:
Example 1: Sorting a list of numbers in ascending order
Call the sorted() function and pass the list as an argument. The output sorted list will be in ascending order.
Example 3: Sorting a list of tuples based on the second element of each tuple
Use a lambda function as the key parameter for sorted(), with the second element of each tuple as the sorting criteria. The sorted list will be in ascending order based on the second element of each tuple.
O(nlog(n)): sorted() function uses a version of the merge sort algorithm called TimSort, which has a worst-case time complexity of O(n log n).
Space Complexity
O(n): The sorted() uses timsort and has an O(n) space complexity because it returns a new list with sorted elements.
Sort and Sorted Best Practices
Here are some tips for using the sort() and sorted() functions in Python:
Consider using built-in functions like min() and max() instead of sort() or sorted() when you only need to find the smallest or largest value in a list.
Always use sort() for in-place sorting.
Consider using another sorting algorithm like merge or heap sort for large datasets.
While sorting strings, be aware of the case sensitivity of the sort and consider using the key parameter with the str. lower() method.
If you need to sort a list of objects based on their properties, consider implementing the lt() method or using the key parameter with a lambda function.
Always use explicit variable and function names to make your sorting code more readable and maintainable.
As of now, you might have gotten the idea of the difference between sort and sorted in Python. Now we move into the FAQ section.
Frequently Asked Questions
Is sort() or sorted() better?
sort() modifies the list in place, while sorted() returns a new sorted list. Both use Timsort for sorting in Python.
What does sorted() do in Python?
sorted() returns a new sorted list from any iterable, leaving the original unchanged.
Which sorting technique is used by sort() and sorted() functions of Python?
Both sort() and sorted() use Timsort, an efficient hybrid sorting algorithm combining merge and insertion sorts.
Does sort () in Python use extra space?
No, the sort() method in Python does not use extra space. It sorts the list in-place, rearranging the existing elements, which means it does not create a new copy of the list or use additional memory.
How many types of sort are there in Python?
Python offers various sorting algorithms, including Timsort (used by sorted() and sort()), QuickSort, MergeSort, BubbleSort, and more. However, Timsort is the most commonly used sorting algorithm in Python's standard library.
Is Python sort () stable?
Yes, Python's sort() method is stable. This means that when sorting elements with equal values, the relative order of those elements will be preserved after sorting, ensuring consistent behavior for sorting algorithms.
Conclusion
In conclusion, the sort and sorted functions are used for sorting lists in Python. Understanding the differences between sort and sorted in Python is essential. While both functions sort a list, their implementation has some differences. Understanding the difference between sort and sorted in Python can help you effectively manipulate lists in your Python programs.