Sort Method in Python – Sorting a list Permanently

Spread the love

In this post you will learn how to sort a list permanently.

Sort in Python –

The sort method in Python change the order of the list permanently either in ascending or descending order.

Syntax of sort method –

list.sort(key=None, reverse=False)

key – Optional. A function to specify the sorting criteria(s)

reverse – optional – reverse=True will sort the list in descending order. By default reverse=False mean list will be sorted in ascending order.

Sort a list in Ascending order –

By default sort method in python sort a list in ascending order.

In [23]: companies = ['Google','Apple','Microsoft','Netflix', 'Facebook']

In [24]: companies.sort()

In [25]: companies
Out[25]: ['Apple', 'Facebook', 'Google', 'Microsoft', 'Netflix']

Sort a list in Descending Order –

To sort a list in descending order, set the reverse parameter to True.

In [26]: companies.sort(reverse=True)

In [27]: companies
Out[27]: ['Netflix', 'Microsoft', 'Google', 'Facebook', 'Apple']

Sort a list by a key –

Sort the list by the length of the company names.

In [28]: def name_length(name):
    ...:     return len(name)

In [29]: companies.sort(key=name_length)

In [30]: companies
Out[30]: ['Apple', 'Google', 'Netflix', 'Facebook', 'Microsoft']

Sort a list by the year a company founded.

In [31]: companies = [
    ...:     {'company':'Apple', 'year': 1976},
    ...:     {'company':'Google','year': 1998},
    ...:     {'company':'Netflix','year': 1997},
    ...:     {'company':'facebook','year':2004},
    ...:     {'company':'Microsoft','year':1975} ]

In [32]: def year_founded(companies):
    ...:     return companies['year']

In [33]: companies.sort(key=year_founded)

In [34]: companies
[{'company': 'Microsoft', 'year': 1975},
 {'company': 'Apple', 'year': 1976},
 {'company': 'Netflix', 'year': 1997},
 {'company': 'Google', 'year': 1998},
 {'company': 'facebook', 'year': 2004}]

Rating: 1 out of 5.

Leave a Reply