How to Sort a list Alphabetically in Python

An alphabetically sorted list will contain all uppercase letters first and lowercase second in the order of the English alphabet.


In Python, we can sort a list alphabetically using the native sorted() function. Pass the list to sort as the first argument and store the output in a variable as sorted() does not modify the original list.


items = ['c', 'C', 'b', 'a', 'd', 'B']

sorted_items = sorted(items)

['B', 'C', 'a', 'b', 'c', 'd']


Ignore Case When sorting a List

The Python sorted() function takes an optional second argument key which we can use to make a case insensitive sort. To this, we will set the value of the key= to str.lower.


items = ['c', 'C', 'b', 'a', 'd', 'B']

sorted_items = sorted(items, key=str.lower)

['a', 'b', 'B', 'c', 'C', 'd']


In the above example, each element in the list is evaluated in its lowercase form.