AppDividend
Latest Code Tutorials

How to Sort List Alphabetically in Python

0

Python has a built-in function called sorted(), which will give you a sorted list from any iterable you feed it. Lists also have a sort() method that will perform the sort in place.

Python list sort()

The list.sort() is a built-in function that sorts the elements of a list in low to high order. If the list is of numbers then by default they will be sorted in increasing order.

data = ['Elle', 'Miles', 'Kratos', 'Joel', 'Peter', 'Nathan']

data.sort()
print(data)

Output

['Elle', 'Joel', 'Kratos', 'Miles', 'Nathan', 'Peter']

You can see that it sorted alphabetically in ascending order by default.

Python sort list alphabetically

To sort a list alphabetically in Python, use the sorted() function. The sorted() method sorts the given iterable object in a specific order, which is either ascending or descending.

The sorted(iterable, key=None) takes an optional key that specifies how to sort. To disregard capitalization when sorting a list, set key to str.

data = ['Elle', 'Miles', 'Kratos', 'Joel', 'Peter', 'Nathan']

print(sorted(data))

Output

['Elle', 'Joel', 'Kratos', 'Miles', 'Nathan', 'Peter']

And it returns a list of strings in ascending order.

One thing to note here is that we have not mixed a list with upper and lowercase strings. Let’s do that and see the output.

data = ['Elle', 'miles', 'kratos', 'Joel', 'peter', 'Nathan']

print(sorted(data))

Output

['Elle', 'Joel', 'Nathan', 'kratos', 'miles', 'peter']

As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter.

 If you want to sort them independently, add the key parameter.

data = ['Elle', 'miles', 'kratos', 'Joel', 'peter', 'Nathan']

print(sorted(data, key=str.lower))

Output

['Elle', 'Joel', 'kratos', 'miles', 'Nathan', 'peter']

To reverse the order of the list, add the reverse argument and set it to True.

data = ['Elle', 'miles', 'kratos', 'Joel', 'peter', 'Nathan']

print(sorted(data, reverse=True))

Output

['peter', 'miles', 'kratos', 'Nathan', 'Joel', 'Elle']

The list.sort() will sort it alphabetically. You can add reverse=False/True in the brackets to reverse the order of items: list.sort(reverse=False).

That is it for the Python sort list alphabetically tutorial.

See also

Python sort set

Sort dictionary by value

Sort dictionary by key

Python ordered set

Leave A Reply

Your email address will not be published.

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