89DEVs

# Python list.sort() method

```list sort() method
The sort() method of Python lists sorts the elements of the given list in ascending or descending order.
The default is to sort in ascending order. To sort in descending order, use the reverse parameter (first argument) of the list sort() method.

sort a list in Python
To sort a  list in Python, use the list.sort() method as shown below.

```
# sort a list in Python
cba = ['c', 'b', 'a']
cba.sort()
print(cba)
```

In this example, the list cba contains three string values c, b and a.
Then, the sort() method is called on the cba list.
Finally, the sorted list is printed and the results are in ascending order by default.

['a', 'b', 'c']

sort a list in descending order
The Python list method sort() sorts by default in ascending order. To sort in descending order, use the reverse parameter as shown below.

```
# sort a list in descending order
abc = ['a', 'b', 'c']
abc.sort(reverse=True)
print(abc)
```

In this example, the list abc contains three string values a, b and c.
Then, the sort() method is called and the parameter reverse is set to True.
Finally, the sorted list is printed and the result is the list in reversed order.

['c', 'b', 'a']

syntax of list.sort()
The syntax of the list.sort() method is:

`list.sort([key, reverse])`

arguments of list.sort()
The list.sort() method has two optional parameters, none of them is required.

parameter
required
description

reverse
optional
if True, the list is sorted in reversed order

key
optional
a function used as a key for the sorting

return values of list.sort()
The sort() method doesn't return any value. It changes the list it is called on.

time complexity
The time complexity of list.sort() is O(n).

FAQ

How do you sort a list in Python?

To sort a list in Python, use the list.sort() method as shown above.

```