Follow

Follow
Python sort vs sorted - Detailed Comparison With Code

Python sort vs sorted - Detailed Comparison With Code

Sachin Pal's photo
Sachin Pal
·Apr 6, 2023·

7 min read

Play this article

Table of contents

  • sort()
  • sorted()
  • Difference
  • Conclusion

We'll compare Python list sort() and sorted() functions in this article. We'll learn about these functions, such as what they are and how they differ programmatically and syntactically.

Python sort() and sorted() are used to sort the data in ascending or descending order. Their goals are the same but are used in different conditions.

sort()

The Python sort() function is connected to the Python list and by default, sorts the list's contents in ascending order.

# List of names
data = ['Sachin', 'Yogesh', 'Yashwant', 'Rishu']
print(f'Original Data: {data}')

# Using list.sort() function
data.sort()
# Printing sorted data
print(f'Sorted Data: {data}')

----------
Original Data: ['Sachin', 'Yogesh', 'Yashwant', 'Rishu']
Sorted Data: ['Rishu', 'Sachin', 'Yashwant', 'Yogesh']

The code above sorts the names in ascending order within the list data. That was the most fundamental use of the list sort() function. We'll see more examples where we'll manipulate the function's parameters.

Syntax

list.sort(reverse=False, key=None)

Here

reverse - Defaults to False. If reverse=True, the data will be sorted in descending order.

key - Defaults to None. We can specify a user-defined function to customize the sorting.

Examples

We'll play around with these parameters and try with data having different data types to get a better understanding of this function.

Example 1 - List having different characters

# Original List
typ_data = ['$', '45', '3j+5', 'Hello']
print(f'Original Data: {typ_data}')

# Sorting the list
typ_data.sort()
# Printing sorted list
print(f'Sorted Data: {typ_data}')

----------
Original Data: ['$', '45', '3j+5', 'Hello']
Sorted Data: ['$', '3j+5', '45', 'Hello']

Example 2 - List containing the different data types

In the following example, data is a list that contains tuples and we sorted the data in descending order.

# List containing tuple data
data = [
    ('Hey', 'There'),
    ('Geeks', 'Welcome'),
    ('To', 'GeekPython')
]
# Printing the type of list item
print(f'Type: {type(data[0])}')
# Sorting the data in descending order
data.sort(reverse=True)
# Printing modified data
print(data)

----------
Type: <class 'tuple'>
Sorted Data: [('To', 'GeekPython'), ('Hey', 'There'), ('Geeks', 'Welcome')]

What if we specify a similar name for the first values of the tuple?

# List containing tuple data with first values having similar name
data = [
    ('item', 2),
    ('item', 1),
    ('item', 3)
]
# Printing the type of list item
print(f'Type: {type(data[0])}')
# Sorting the data in descending order
data.sort(reverse=True)
# Printing modified data
print(f'Sorted Data: {data}')

----------
Type: <class 'tuple'>
Sorted Data: [('item', 3), ('item', 2), ('item', 1)]

The tuples were sorted based on the second value because sort() cannot perform sorting on similar values, or more specifically, how can data be sorted in ascending or descending order if they are all similar?

Example 3 - Using a user-defined function

# List containing dictionary data
data = [
    {'fruit': 'strawberry', 'price': 100},
    {'fruit': 'banana', 'price': 91},
    {'fruit': 'mango', 'price': 132},
    {'fruit': 'cherry', 'price': 82},
]

print(f'Original Data: {data}')

# Function for sorting by key 'price'
def sort_dict_by_price(item):
    return item['price']

# Sorting data using the user-defined sorting function
data.sort(key=sort_dict_by_price)
print('-'*20)
# Printing the data
print(f'Sorted Data: {data}')

We've written a function called sort_dict_by_price that takes a parameter item, which is our dictionary itself, and returns the values of the key 'price'.

This function was passed to the key parameter, which will sort the data based on the price in ascending order.

Output

Original Data: [{'fruit': 'strawberry', 'price': 100}, {'fruit': 'banana', 'price': 91}, {'fruit': 'mango', 'price': 132}, {'fruit': 'cherry', 'price': 82}]
--------------------
Sorted Data: [{'fruit': 'cherry', 'price': 82}, {'fruit': 'banana', 'price': 91}, {'fruit': 'strawberry', 'price': 100}, {'fruit': 'mango', 'price': 132}]

Instead of explicitly defining the sort_dict_by_price function, we could have used the lambda function in the above code.

# List containing dictionary data
data = [
    {'fruit': 'strawberry', 'price': 100},
    {'fruit': 'banana', 'price': 91},
    {'fruit': 'mango', 'price': 132},
    {'fruit': 'cherry', 'price': 82},
]

print(f'Original Data: {data}')

# Sorting data using the lambda function
data.sort(key=lambda item: item['fruit'])
print('-' * 20)
# Printing the data
print(f'Sorted Data: {data}')

We changed the code above and passed the lambda function to the key. The expression lambda item: item['fruit'] is equivalent to the previous code's sort_dict_by_price function.

Output

Original Data: [{'fruit': 'strawberry', 'price': 100}, {'fruit': 'banana', 'price': 91}, {'fruit': 'mango', 'price': 132}, {'fruit': 'cherry', 'price': 82}]
--------------------
Sorted Data: [{'fruit': 'banana', 'price': 91}, {'fruit': 'cherry', 'price': 82}, {'fruit': 'mango', 'price': 132}, {'fruit': 'strawberry', 'price': 100}]

Example 4 - Sorting tuple data by specifying sorting criteria

In the following example, data is a list containing tuples and we sorted the data in descending order based on the first items of the tuple.

# List containing tuple data
data = [
    ('strawberry', 100),
    ('banana', 91),
    ('mango', 132),
    ('cherry', 82),
]

print(f'Original Data: {data}')

# Sorting data based on first value in descending order
data.sort(key=lambda item: item[0], reverse=True)
print('-' * 20)
# Printing the data
print(f'Sorted Data: {data}')

Output

Original Data: [('strawberry', 100), ('banana', 91), ('mango', 132), ('cherry', 82)]
--------------------
Sorted Data: [('strawberry', 100), ('mango', 132), ('cherry', 82), ('banana', 91)]

sorted()

Python sorted() function is used to sort the iterable data. By default, this function sorts the data in ascending order.

# Tuple data
tuple_data = ((4, 's'), (1, 'q'), (3, 'z'), (4, 'a'))
print(f'Original: {tuple_data}')
# Using sorted function
sorting = sorted(tuple_data)
print('-'*20)
# Printing the sorted data
print(f'Sorted: {sorting}')

We have nested tuple data stored in the variable tuple_data, used the sorted() function with our iterable as a parameter, and then printed the sorted data.

Output

Original: ((4, 's'), (1, 'q'), (3, 'z'), (4, 'a'))
--------------------
Sorted: [(1, 'q'), (3, 'z'), (4, 'a'), (4, 's')]

The data were sorted based on the first item of the tuple tuple_data.

Syntax

sorted(iterable, key=None, reverse=False)

Here

iterable - Required. Any iterable data

key - defaults to None. To specify the sorting criteria.

reverse - Defaults to False. When set to True, the data will be sorted in descending order.

Examples

We have data of various data types that are all iterable; we'll sort them using the sorted() function.

list_data = [43, 21, 2, 34]
print(f'Sorted List: {sorted(list_data)}')

# Seperator
print('-'*20)

tuple_data = (('x', 3), ('w', 1), ('1', 4))
print(f'Sorted Tuple: {sorted(tuple_data)}')

# Seperator
print('-'*20)

dict_data = {9: 'G', 1: 'V', 4: 'E'}
print(f'Sorted Dictionary Keys: {sorted(dict_data)}')
print(f'Sorted Dictionary Values: {sorted(dict_data.values())}')
print(f'Sorted Dictionary Items: {sorted(dict_data.items())}')

Output

Sorted List: [2, 21, 34, 43]
--------------------
Sorted Tuple: [('1', 4), ('w', 1), ('x', 3)]
--------------------
Sorted Dictionary Keys: [1, 4, 9]
Sorted Dictionary Values: ['E', 'G', 'V']
Sorted Dictionary Items: [(1, 'V'), (4, 'E'), (9, 'G')]

Example 2 - Using key and reverse parameters

# Tuple data
tuple_data = (
    ('Mango', 25),
    ('Walnut', 65),
    ('Cherry', 10),
    ('Apple', 68),
)

print(f'Original: {tuple_data}')
# Separator
print('-'*20)

# Function for grabbing 2nd item from the data
def sorting_tup_data(item):
    return item[1]

# Sorting based on sorting criteria in descending order
sorting = sorted(tuple_data, key=sorting_tup_data, reverse=True)
print(f'Sorted: {sorting}')

Output

Original: (('Mango', 25), ('Walnut', 65), ('Cherry', 10), ('Apple', 68))
--------------------
Sorted: [('Apple', 68), ('Walnut', 65), ('Mango', 25), ('Cherry', 10)]

Due to the use of the key parameter where we passed the custom function, the tuple was sorted based on the second item and data was sorted in descending order because the reverse was set to True.

Difference

sort()sorted()
Used to sort the Python List.Used to sort any iterable data such as List, Tuple, Dictionary and more.
Takes two parameters: key and reverse.Takes three parameters: iterable, key and reverse.
It is a List function(list.sort()) and can only work with Lists.It is a function to sort any data which can be iterated.
sort() modifies the original list.sorted() doesn't modify the original data instead it returns the new modified data.

Conclusion

We've seen a comparison of the list sort() and sorted() functions. We've coded the examples to understand how these functions work. Both functions are used to sort data, but the sort() function only sorts Python lists, whereas the sorted() function sorts iterable data.

We've also seen the differences between the two in a table format.


🏆Other articles you might be interested in if you liked this one

Comparing the list reverse and reversed functions.

8 different ways to reverse a Python list.

NumPy argmax() and TensorFlow argmax() - Are they similar?

Execute your code dynamically using the exec() in Python.

Perform high-level file operations on files in Python.

Number your iterable data using the enumerate() in Python.

Understanding args and kwargs in function parameter in Python.


That's all for now

Keep Coding✌✌

Did you find this article valuable?

Support Sachin Pal by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this