How to sort list in Python

Python List

In this post, we will learn how to sort list in Pythonle ways to sort a list in Python with examples. How to sort number list in Python 3, How can you sort a list of tuples by the Second element .The difference in both is that sort() updates the original list with the sorted results, Whereas sorted() returns a new list with the modified list.

Ways to sort list in Python


  • How to sort number list in Python3
  • How to sort list using function
  • How to sort list using lambda expression
  • How sort list of list by Second element
  • How to sort list without using sort() function
  • sort list of objects in python

1. How to sort number list in Python 3


In this example, We can sort the list of numbers in ascending and descending order by using the sort and sorted() method. By default list.sort() method sort list in ascending order.

Python Program to sort number list Ascending order

mylist = [20,42,60,4,70.5,10.1]
mylist.sort()
print(mylist)

Output

[4, 10.1, 20, 42, 60, 70.5]

Python Program to sort number list Descending order

mylist = [20,42,60,4,70.5,10.1]
mylist.sort(reverse=True)
print(mylist)

Output

[70.5, 60, 42, 20, 10.1, 4]

2. How to sort list using function


To sort the list of tuples by the second element we can define our own key function to be used by our custom sort.

Python Program to sort list using function

def seconditem_sort(item):
     return item[1]

mylist = [("apple", 25), ("banana", 20), ("orange", 5)]
mylist.sort(key=seconditem_sort)
print(mylist)

Output

[('orange', 5), ('banana', 20), ('apple', 25)]

3. Sort list using lambda expression in Python


You can achieve the above same results with less and neater code, with help of lambdas function The sorting list by lambda expression we are passing lambda expression as a key to sort() method.

Python Program to sort list using lambda expression

mylist = [("apple", 25), ("banana", 20), ("orange", 5)]
mylist.sort(key=lambda item:item[1])
print(mylist)

Output

[('orange', 5), ('banana', 20), ('apple', 25)]

4 . How sort list of list by Second element


We can sort the list of lists by using the above methods we have used for the list of tuples.Let us understand with an examples

Python Program to sort list of list by second element

mylist = [["dog", 25], ["cat", 20], ["bull", 5]]
mylist.sort(key=lambda item:item[1])
print(mylist)

Output

[['bull', 5], ['cat', 20], ['dog', 25]]

5. Sort list in python without using sort() function


In this example to sort list without built in sort() method.Let us understand how it working

  • using the while loop to iterate over the all elements of list.
  • We access the value at list first index and assign it to min_val variable.
  • The for loop iterate over the list elements comparing the each value with min_val when value is less assign it to min_val and appending it to result list and removing from original list

Python Program to sort list without using sort() function

myLst = [20,42,60,4,70.5,10.1]
res_lst = []

while myLst:
    min_val = myLst[0]  
    for item in myLst: 
        if item < min_val:
            min_val = item
    res_lst.append(min_val)
    myLst.remove(min_val)    

print(res_lst)

Output

[4, 10.1, 20, 42, 60, 70.5]

6. Sort List of Objects in Python


Sometime we have data collection as form of generic object and we will have to sort the object based on some custom criteria.Once again here come the key parameter,to make it easy and achieve it.We have below fruits class with name and price attribute

class fruits:
    def __init__(self, name, price):
        self.fruitname = name
        self.price = price

Here we are creating some fruits class objects and then in the list and adding them in the list.

app = fruits('apple',60)
ban = fruits('banana',30)
oran = fruits('orange',50)
fruitslist = [app,ban,oran]

Let us sort the list alphabetically  based on name attribute

fruitslist.sort(key=lambda att: att.fruitname)
print([item.fruitname for item in fruitslist])

Output

['apple', 'banana', 'orange']

Let we sort the list based on price attribute

fruitslist.sort(key=lambda att: att.price)
print([item.price for item in fruitslist])

Output

[30, 50, 60]

Summarry

In this post,we have understood How to sort list in Python.We can use any of above mention methods to sort a list in python.