Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Sorting in Python
2.1.
CODE
3.
Python
3.1.

3.2.
OUTPUT
3.3.
EXPLANATION
4.
Sort() Function in Python
4.1.
Syntax
4.2.
Example 1: Sorting a list of integers in ascending order
4.2.1.
CODE
4.3.
Python
4.3.1.
OUTPUT
4.4.
Example 2: Sorting a list of strings in alphabetical order
4.4.1.
CODE
4.5.
Python
4.5.1.
OUTPUT
4.6.
Example 3: Sorting a list of tuples based on the second element
4.6.1.
CODE
4.7.
Python
4.7.1.
OUTPUT
4.8.
Example 4: Sorting a list of custom objects based on a specific property
4.8.1.
CODE
4.9.
Python
4.9.1.
OUTPUT
4.9.2.
Time Complexity
4.9.3.
Space Complexity
5.
Sorted() Function in Python
5.1.
Syntax
5.2.
Example 1: Sorting a list of numbers in ascending order
5.2.1.
CODE
5.3.
Python
5.3.1.
OUTPUT
5.4.
Example 2: Sorting a list of strings in ascending order
5.4.1.
CODE
5.5.
Python
5.5.1.
OUTPUT
5.6.
Example 3: Sorting a list of tuples based on the second element of each tuple
5.6.1.
CODE
5.7.
Python
5.7.1.
OUTPUT
5.8.
Example 4: Sorting a dictionary by keys in ascending order
5.8.1.
CODE
5.9.
Python
5.9.1.
OUTPUT
5.9.2.
Time Complexity
5.9.3.
Space Complexity
6.
Key Differences Between Sort and Sorted in Python
7.
Sort and Sorted Best Practices
8.
Frequently Asked Questions
8.1.
Is sort faster than sorted Python?
8.2.
Does sort () in Python use extra space?
8.3.
How many types of sort are there in Python?
8.4.
Is Python sort () stable?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

# Difference Between Sort and Sorted in Python

## Introduction

Hey, Ninjas! Do you need clarification about the difference between sort and sorted in Python? Whether new to coding or experienced, this article will explain sort and sorted functions in Python that help sort data. By the end of this article, you'll understand how these functions work differently.

Let's explore the difference between sort and sorted functions in Python together!

## 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.

• 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)``

#### EXPLANATION

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.

• Python

### Python

``numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]numbers.sort()print(numbers)``

### Example 2: Sorting a list of strings in alphabetical order

The list of strings will be sorted in place. The sorted list will be in alphabetical order based on the ASCII values of the characters.

• Python

### Python

``languages = ['Python', 'Java', 'Ruby', 'C#', 'JavaScript', 'PHP', 'Swift']languages.sort()print(languages)``

### 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.

• Python

### Python

``numbers = [('Ram', '21'), ('Shyam', '10'), ('Sita', '7'), ('Gita', '30')]def get_second_element_as_int(t):    return int(t[1])numbers.sort(key=get_second_element_as_int)print(numbers)``

### 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.

• 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)``

#### Time Complexity

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.

• Python

### Python

``numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]sorted_numbers = sorted(numbers)print(sorted_numbers)``

### Example 2: Sorting a list of strings in ascending order

The output sorted list will be in alphabetical order based on the ASCII values of the characters.

• Python

### Python

``languages = ['Python', 'Java', 'Ruby', 'C#', 'JavaScript', 'PHP', 'Swift']sorted_languages = sorted(languages)print(sorted_languages)``

### 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.

• Python

### Python

``numbers = [('Ram', '21'), ('Shyam', '10'), ('Sita', '7'), ('Gita', '30')]sorted_numbers = sorted(numbers, key=lambda t: int(t[1]))print(sorted_numbers)``

### Example 4: Sorting a dictionary by keys in ascending order

Call the sorted() function and pass the dictionary keys as an argument.

Access the corresponding values in the dictionary as you iterate through the sorted keys.

• Python

### Python

``my_dict = {'d': 4, 'a': 1, 'c': 3, 'b': 2}sorted_dict = dict(sorted(my_dict.items()))print(sorted_dict)``

#### Time Complexity

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.

Also see, Convert String to List Python

## Key Differences Between Sort and Sorted in Python

The following table summarizes the key differences between sort and sorted functions in Python:

## Sort and Sorted Best Practices

Here are some tips for using the sort() and sorted() functions in Python:

1. 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.

2. Always use sort() for in-place sorting.

3. Consider using another sorting algorithm like merge or heap sort for large datasets.

4. While sorting strings, be aware of the case sensitivity of the sort and consider using the key parameter with the str. lower() method.

5. 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.

6. 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.
Must Read  C Program to Reverse a Number

## Frequently Asked Questions

### Is sort faster than sorted Python?

sort() is generally faster than sorted() in Python because it sorts the list in-place by modifying the original list. On the other hand, sorted returns a new sorted list while preserving the original list.

### 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.

If you want to learn more about this topic and go into more detail, we recommend reading the articles attached.

Also check out the Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.

Happy Coding!

Live masterclass