Difference Between sort() and sorted() in Python for Efficient Data Sorting

Difference Between sort() and sorted() in Python for Efficient Data Sorting

5 mins read137 Views Comment
Syed Aquib Ur
Syed Aquib Ur Rahman
Assistant Manager
Updated on Jul 18, 2024 17:58 IST

The main difference between sort() and sorted() in Python lies in how you perform sorting on lists. “sort()” modifies the original list in place, while “sorted()” creates a new sorted list. We will show how.

2023_10_sort-vs-sorted-in-python.jpg

When you prioritise preserving your data in a programming language like Python, you use sorted() to create a new list. Alternatively, to optimise memory or work with large datasets, sort() is useful. The original list’s order is changed, but no new list is created.

Beyond this difference between sort() and sorted() in Python, know that these are two basic methods of sorting data. These are explored in many of the Python courses on our platform. But this blog will uncover some doubts about the minute differences that you may have.  

Comparison Table: sort() vs sorted() in Python

Aspect sort() sorted()
Operation Type In-Place Sorting Non-Destructive Sorting
Original Data Modification Alters the original list Leaves the original list intact
Memory Efficiency Minimal memory usage Creates a new sorted list
Applicability Only for lists Versatile, works with various iterables (e.g., lists, tuples, strings)
Custom Sorting Criteria Can use a custom sorting key Can use a custom sorting key
Performance Considerations Fast for large datasets, efficient memory usage May use additional memory for the new list
Binary Search Efficiency Ideal for binary search algorithms on sorted data Not suitable for binary search, as it creates a new list
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Explaining sort() Function

The sort() function is an in-place sorting method which modifies the original list. When you call list.sort(), the elements are reordered directly within the list. No new list is created. 

In-place sorting is advantageous when working with large datasets. Even when preserving the original order of elements is not a priority.

How sort() Function Works

To use sort(), simply call it on a list and specify the sorting order. 

By default, it sorts the list in ascending order. 

But you can also sort in descending order by setting the ‘reverse’ parameter to ‘True’.

Example of Using sort() Function 

When learning to use sort function in Python, you must know about ascending and descending order lists. 

Sorting in ascending order (from smallest to largest) is suitable when you want to showcase a progression, highlight the lowest values, or emphasize growth over time. 

On the other hand, sorting in descending order (from largest to smallest) is used when you want to highlight the highest values, emphasize a decline, or present data in reverse chronological order.

Here is how to SORT IN ASCENDING ORDER


 
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers)
Copy code

ASCENDING ORDER OUTPUT is [1, 2, 5, 5, 6, 9]

Now, to SORT LIST IN DESCENDING ORDER, all you have to do is set the reverse parameter to ‘True’.


 
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort(reverse=True)
print(numbers)
Copy code

DESCENDING ORDER OUTPUT is [9, 6, 5, 5, 2, 1]

Explaining sorted() Function

The sorted() function creates a new list with sorted elements. It leaves the original list unchanged. This makes sorted() a non-destructive sorting method.

How sorted() Function Works

Using sorted() is straightforward. You pass the iterable to be sorted as an argument, and it returns a new sorted list.

Explore career-oriented courses after 12th. Uncover how online degree programs can shape your professional trajectory.

Examples of Using sorted() Function

New Sorted List


 
names = ["Alice", "Bob", "Eve", "David"]
sorted_names = sorted(names)
print(sorted_names)
Copy code

OUTPUT: [‘Alice’, ‘Bob’, ‘David’, ‘Eve’]

Sorting a List of Strings

Alphabetically – see how it’s done.


 
fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits)
print(sorted_fruits)
Copy code

OUTPUT: [‘apple’, ‘banana’, ‘cherry’, ‘date’]

Most Important Comparisons Between sort() and sorted() to Remember

Return Value: sort() vs sorted()

The primary difference between sort() and sorted() is the return value. sort() returns None because it modifies the original list in-place. sorted(), on the other hand, returns a new sorted list.

Mutability of the Original List: sort() vs sorted()

sort() directly modifies the original list, while sorted() keeps the original list intact and creates a new sorted list. This means that if you need to preserve the original order, sorted() is the safer choice.

Usage with Different Iterables: sort() vs sorted()

While both sort() and sorted() work with lists, sorted() can be used with any iterable, including tuples, strings, and dictionaries, while sort() is specific to lists.

Why Knowing the Difference Between sort() and sorted() in Python is Crucial

The main reason is time and space complexity. Understanding this helps you choose the most efficient sorting method based on the size of your data and the available memory.

Both sort() and sorted() have an average time complexity of O(n log n), where n is the number of elements in the iterable. This is efficient for most datasets. 

In terms of space complexity, sort() is more memory-efficient because it sorts in-place, while sorted() creates a new list.

Prioritising space complexity is beneficial for resource management. In scenarios with limited memory, knowing the space requirements of different sorting methods is essential. In-place sorting, like list.sort(), can be more memory-efficient. But you need to weigh this against the trade-off of modifying the original data.

Common Scenarios When sort() and sorted() are Preferable

Scenario Preferred Sorting Method Key Considerations
In-Place Sorting with sort() sort() Minimises memory usage. Modifies the original list directly.
Data Preservation with sorted() sorted() Preserves the original data. Suitable for diverse data structures beyond lists.
Custom Sorting Criteria with Both Both sort() and sorted() Allows for tailored sorting criteria using the key parameter.
Efficient Searching with sort() sort() Ideal for binary search algorithms, which require data sorted in ascending order.
Data Presentation and User Expectations Both sort() and sorted() Align sorting with user expectations and the context of data presentation.
Data Analysis and Processing Both sort() and sorted() Choose based on the need to preserve historical data or perform efficient data analysis and aggregation.
Algorithm Selection Based on Performance Varies based on requirements Understand time and space complexity for performance optimisation.

Python’s External Libraries for Advanced Sorting

For advanced sorting needs, external libraries like NumPy provide powerful sorting capabilities. For more complex data manipulation, there are more. See the list below. 

Library / Tool Description
NumPy Advanced sorting algorithms like quicksort and mergesort. Suitable for numerical and scientific computing.
Pandas Advanced sorting and ranking functions for tabular data and time series analysis.
SciPy Extends NumPy’s capabilities, providing additional sorting functionalities for scientific and technical applications.
Cython A superset of Python that allows integrating C or C++ code for custom sorting algorithms.
Algorithms in sortedcontainers Provides data structures like sorted lists and sets with fast insertions and deletions.
heapq Module Part of Python’s standard library, allowing heap-based operations and sorting in a priority queue.
functools.cmp_to_key Function Converts a comparison function into a key function for custom sorting.
operator Module Provides functions for itemgetter, attrgetter, and methodcaller, useful for sorting complex data structures.

FAQs

How do I sort in descending order using sort() and sorted()?

For sort(), you can use the reverse parameter:
numbers.sort(reverse=True)
For sorted(), you can also use the reverse parameter:
sorted_numbers = sorted(numbers, reverse=True)

Are there any external libraries in Python that offer advanced sorting capabilities?

Yes, several external libraries provide advanced sorting functionalities:

  • NumPy: Offers advanced sorting algorithms like quicksort and mergesort.
  • Pandas: Provides sorting and ranking functions for tabular data.
  • SciPy: Extends NumPy's capabilities with additional sorting functionalities.
  • sortedcontainers: Offers data structures like sorted lists and sets with fast operations.
About the Author
author-image
Syed Aquib Ur Rahman
Assistant Manager

Aquib is a seasoned wordsmith, having penned countless blogs for Indian and international brands. These days, he's all about digital marketing and core management subjects - not to mention his unwavering commitment ... Read Full Bio