Sorted in Python – Sort a List Temporarily in Python

Spread the love

In this post, you will learn how to sort a list temporarily in python

Sorted Method in Python –

The sorted method in python sorts a list temporarily in ascending or descending order.

Syntax of sorted –

sorted(iterable, key=None, reverse=False)

iterable – Required. A sequence to sort, list, dictionary, tuple etc.

Key – Optional. A function that is used for sorting

reverse – Optional. By default sort in ascending order (reverse=False). To sort in descending order Set reverse=True.

Sort a list in ascending Order –

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

In [37]: sorted(companies)
Out[37]: ['Apple', 'Facebook', 'Google', 'Microsoft', 'Netflix']

Sort a list in descending Order –

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

In [39]: sorted(companies, reverse=True)
Out[39]: ['Netflix', 'Microsoft', 'Google', 'Facebook', 'Apple']

Sort a list by key –

Sort a list by the year they founded.

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

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

In [42]: sorted(companies, key=year_founded)
Out[42]: 
[{'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