×

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.


Related Topics

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

Python Modules List

Python is like an ocean. If you have been working with Python, you might’ve already heard the word module. When we solve a problem in mathematics, there will be several...

3 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Struct Module in Python

What is a structure in Python? An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and...

4 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.