Python Sort - How do we sort list in python?

Published June 09, 2021

In this python programming example we will learn how to sort list in python. In Python we have different ways to sort a list items. The list data type in python has two methods to sort its elements those sort() and sorted() methods. In this example we will learn how to use these two methods to sort list in python.

  1. sort()
  2. sorted()

 

Python sort list elements

 

Using sort() method to sort list

This sort() method will sort the given list elements in ascending or descending order. This sort method perform sorting action on its own object and change the values order of the given list.

This sort() syntax method have two arguments,one is key and other is reverse.

The key is tell the sorting based on the key and reverse is tells the sorting in ascending or descending order.

 

al = ['a','d','e','c','b',"K","A","Z","z"]

al.sort()
print('List in Ascending Order: ', al)

 

This will sort the list in ascending order and print the below output

List in Ascending Order:  ['A', 'K', 'Z', 'a', 'b', 'c', 'd', 'e', 'z']

 

When the sorting process of list takes the words starting with an uppercase letter takes as a higher precedence than words starting with a lowercase letter.

 

To sort the list in descending order we have to pass the reverse parameter as true

al = ['a','d','e','c','b',"K","A","Z","z"]
al.sort(reverse=True)
print('List in Descending Order: ', al)

 

This will print the below output

List in Descending Order:  ['z', 'e', 'd', 'c', 'b', 'a', 'Z', 'K', 'A']

 

Using sorted() method to sort list

This python inbuilt method sorted() will sort the given list similar to sort() method but here is returns new list instead of sorting the original list. This sorted() method perform sort process and returns new list with sorted elements.

 

sortlist = ['a','d','e','c','b',"K","A","Z","z"]
sortedList=sorted(sortlist)

print('Original List : ', sortlist)
print('Sorted List : ', sortedList)

 

This will return below output

Output

Original List :  ['a', 'd', 'e', 'c', 'b', 'K', 'A', 'Z', 'z']

Sorted List :  ['A', 'K', 'Z', 'a', 'b', 'c', 'd', 'e', 'z']

 

To sort list items in descending order we have to pass reverse parameter to true

 

sortlist = ['a','d','e','c','b',"K","A","Z","z"]
sortedList=sorted(sortlist,reverse=True)

print('Original List : ', sortlist)
print('Sorted List : ', sortedList)

 

Output

Original List :  ['a', 'd', 'e', 'c', 'b', 'K', 'A', 'Z', 'z']

Sorted List :  ['z', 'e', 'd', 'c', 'b', 'a', 'Z', 'K', 'A']

 

Related:

15 Python Project Ides for Beginners

Swap two numbers in python

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

338 Views