sort() in Python


In this tutorial, we are going to learn about the sort method of a list. Let's dive into the tutorial. The method sort is used to sort any list in ascending or descending order. There are many cases of sort method with or without optional parameters.

The method sort is an in-place method. It directly changes in the original list

Let's see one by one.

Default sort()

The method sort without any optional parameters will sort the list in ascending order. Let's an example.

Example

 Live Demo

# initializing a list
numbers = [4, 3, 5, 1, 2]
# sorting the numbers
numbers.sort()
# printing the numbers
print(numbers)

Output

If you run the above code, then you will get the following result.

[1, 2, 3, 4, 5]

reverse parameter with sort()

We can sort the list in descending order using reverse optional parameter. Pass a reverse parameter with value True to sort the list in descending order.

Example

 Live Demo

# initializing a list
numbers = [4, 3, 5, 1, 2]
# sorting the numbers in descending order
numbers.sort(reverse=True)
# printing the numbers
print(numbers)

Output

If you run the above code, then you will get the following result.

[5, 4, 3, 2, 1]

key parameter with sort()

The method sort will take another optional parameter called key. The parameter key is used to tell the sort on which value it has to sort the list.

Let's say we have a list of dictionaries. We have to sort the list of dictionaries based on a certain value. In this case, we pass key as a parameter with a function that returns a specific value on which we have to sort the list of dictionaries.

Example

# initializing a list
numbers = [{'a': 5}, {'b': 1, 'a': 1}, {'c': 3, 'a': 3}, {'d': 4, 'a': 4}, {'e''a': 2}]
# sorting the list of dict based on values
numbers.sort(key= lambda dictionary: dictionary['a'])
# printing the numbers
print(numbers)

Output

If you run the above code, then you will get the following result.

[{'b': 1, 'a': 1}, {'e': 2, 'a': 2}, {'c': 3, 'a': 3}, {'d': 4, 'a': 4}, {'a':

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 11-Jul-2020

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements