Last modified: May 01, 2019

Sorting a List in Python with example

Today, we'll see how to sort and reverse a list.

Sorting a list by default

With the sort() method, we can sort a list by default.

Syntax:


 list.sort(reverse=True|False, key=Func)   

Example:


list_a =  ['cat', 'table', 'apple', 'dog']
list_a.sort()
print(list_a)

Output:

['apple', 'cat', 'dog', 'table']

As you can see, the list has been ordered.


Let's see another example.


list_a =  ['cat3', 'cat2', 'apple', 'dog', "2"]
list_a.sort()
print(list_a)

Output:

['2', 'apple', 'cat2', 'cat3', 'dog']

Reversing a list in python

reverse(): is a method that reverses a list.

Syntax:


#syntax
list.reverse()   

Example:


list_a =  ['cat', 'table', 'apple', 'dog']
list_a.reverse()
print(list_a)

Output :

['table', 'cat', 'dog', 'apple']

Sort and reverse List

Now, let's see sort and reverse a list at once.

Syntax:


list.sort(reverse=True|False)

example:


list_a =  ['cat', 'table', 'apple', 'dog']
list_a.sort(reverse=True)
print(list_a)

output:

['table', 'dog', 'cat', 'apple']


see you later!