×

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

Managing Multiple Python Versions With pyenv

Introduction If you had ever wished to assist to an application that makes use of several different Python versions but weren't sure whether you would quickly test them all? Do you...

4 minutes read.

Sentence to python vector

Conversion of a Sentence to Vector in Python Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python. Python Vector: Putting simply,...

3 minutes read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Python System Requirements

Introduction As we know, Python is a popular programming language usually used to write scripts for operating systems. It’s handy adequate for utilizing in web development and application design. In this article,...

2 minutes 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.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Crash Course on Python by Google

There is a new, free Python programming course offered by Google on Coursera. No programming experience is necessary. There are numerous Python courses available, but when you learn that Google is...

5 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Poolmanager in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python String isalpha() method

Python String isalpha() method The string.isalpha () method in Python returns a boolean value true if all characters in the  string are alphabetic else for any other value it returns false. Syntax isalpha()  Parameter NA Return This...

1 minute read.

Python Glob

Methods for matching files that include particular patterns in accordance with UNIX shell-related expansion rules are referred to as "glob" methods. Similar methods for finding, locating, and searching for all of...

12 minutes read.