SORTING A LIST IN PYTHON

problem

You have a list of items in Python and you wish to sort them, e.g. put them in ascending order. If we assume we have a list of numbers, that would be from the lowest to the greatest (ascending), or vice versa (descending).

SOLUTION

Let’s assume we have the following list of integers.

sorting.py
				
					numbers = [1,90,-22,891,87,44,22,2,4,3,2,1,0]

				
			

In order to sort the list, we can simply use the built-in function sort() as follows:

sorting.py
				
					numbers.sort()

				
			

This will sort the items inside the list and update the list. It will not return a new list but will affect the current list.

So if we now print the list we can see the items are sorted in ascending order.

sorting.py
				
					numbers = [1,90,-22,891,87,44,22,2,4,3,2,1,0]
numbers.sort()
print(numbers)
				
			
output
python sort list
SORTING IN DESCENDING ORDER

Now, if we wish to sort the items of a list in descending order, i.e. from the greatest to the lowest, we can simply do it by passing a boolean parameter to the sort() function as follows:

sorting.py
				
					numbers.sort(reverse=True)
				
			

If we go and print it now:

sorting.py
				
					numbers.sort(reverse=True)
print(numbers)
				
			
output
python sort list descending
reversing items

Now, if we wish to simply reverse the order of the items in the list we can use the reverse() function as follows:

sorting.py
				
					items = ['one','two','three']
items.reverse()
				
			

It will reverse all the items in the list. If we go and print it now:

sorting.py
				
					print(items)
				
			
output
python list.reverse()

conclusion

In this post we saw how simple it is to sort a list of data in Python. We can do both orders ascending and descending order out of the box.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x