In this post, we will learn how to sort a list in Python with examples. We will also cover How to sort a number list in Python 3, How can you sort a list of tuples by the Second element . The difference between the sort() or sorted method is that sort() updates the original list with the sorted results, Whereas sorted() returns a new list, takes a iterable(list) as an agrument.
Ways to sort a list in Python
- How to sort a number list in Python3
- How to sort a list using the function
- How to sort a list using lambda expression
- How to sort a list of lists by the Second element
- How to sort a list without using the sort() function
- sort list of objects in python
1. How to sort a list in Python3
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. To sort a list in descending order we have to pass an argument reverse=True to the sort() method.
Python Program to sort a number list Ascending order
mylist = [20,42,60,4,70.5,10.1]
mylist.sort()
print(mylist)
#using sorted method
reslst = sorted(mylist)
print('Using sorted method:',reslst)
Output
[4, 10.1, 20, 42, 60, 70.5]
Using sorted method : [4, 10.1, 20, 42, 60, 70.5]
Python Program to sort a number list Descending order
mylist = [20,42,60,4,70.5,10.1]
mylist.sort(reverse=True)
print(mylist)
##using sorted method
reslst = sorted(mylist, reverse=True)
print('Using sorted method:',reslst)
Output
[70.5, 60, 42, 20, 10.1, 4]
Using sorted method: [70.5, 60, 42, 20, 10.1, 4]
2. How to sort a list in Python 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.
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. How to Sort a list in Python using lambda expression
You can achieve the same above results with less and neater code, with help of the lambdas function The sorting list by lambda expression we are passing lambda expression as a key to sort() method.
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 to sort a list of lists by the 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
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
Sometimes we have to sort the python list without using in built function.We will follow below steps to sort a list in python.
- The while loop iterates over all elements of the given list.
- We access the value at the list first index and assign it to a min_val variable.
- The for loop iterates over the list elements comparing each value with min_val when the value is less assign it to min_val and append it to result in a list and removing from the original list
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.How to Sort a List of Objects in Python
Sometimes we have data collection as a form of generic object and we will have to sort the object based on some custom criteria. Once again here comes 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 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 the name attribute
fruitslist.sort(key=lambda att: att.fruitname)
print([item.fruitname for item in fruitslist])
Output
['apple', 'banana', 'orange']
Let us sort the list based on the price attribute
fruitslist.sort(key=lambda att: att.price)
print([item.price for item in fruitslist])
Output
[30, 50, 60]
Summary
In this post, we have understood How to sort a list in Python. We can use any of above mention methods to sort a list in python.