AppDividend
Latest Code Tutorials

# Python List Sort Example | sort() Method Tutorial

Python List Sort Example | sort() Method Tutorial is today’s topic. The list sort() method sorts the list ascending by default. You can also make the function to decide the sorting criteria. The sort() method sorts the elements of a given list in the specific order either Ascending or Descending. The sort() method doesn’t return any value. Instead, it changes the original list.

## Python List Sort Example

The syntax of sort() method is following.

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

The reverse parameter value is optional, and reverse=True will sort the list descending. The default is reverse=False.

The key parameter value is optional, and it is the function to specify the sorting criteria.

See the following example.

## Python List Sort() in Ascending Order

Let us see the by default sorting in the list.

```# app.py

GoT = ['Jon', 'Tyrion', 'Daenerys']
GoT.sort()
print (GoT)```

See the output below.

## Python List Sort() in Descending Order

Now to arrange descending order, we need to add reverse=True in the sort() method’s parameter.

```# app.py

GoT1 = ['Jon', 'Tyrion', 'Daenerys']
GoT1.sort(reverse=True)
print (GoT1)```

See the output.

## Sort the list using the key

Let us take a function criteria to sort the list. We sort the list based on the length of the string and sort the descending order based on the length.

```# app.py

def criteria(item):
return len(item)

GoT2 = ['Jon', 'Tyrion', 'Daenerys']
GoT2.sort(reverse=True, key=criteria)
print (GoT2)```

See the output.

Finally, Python List Sort Example | sort() Method Tutorial is over.

This site uses Akismet to reduce spam. Learn how your comment data is processed.