Python sort list of strings | How to sort a list of strings Example code

Using Python in-built sort method you can sort lists in alphabetical/reverse order, Based on length or number value.


Examples sort list of strings in Python

Simple python examples code:-

Using sort() function

This modifies your original list (i.e. sorts in place). To get a sorted copy of the list, without changing the original, use the sorted() function:

mylist = ["B", "C", "A", "D", "E"]


Python sort list of strings

sorted() function example

for x in sorted(mylist):
    print x

Python Sort by the length of strings

Using sort() function with key as len

mylist = ["BBB", "CC", "AAAA", "DD", "EEEEE"]
mylist.sort(key = len)

Output: [‘CC’, ‘DD’, ‘BBB’, ‘AAAA’, ‘EEEEE’]

Sort string by an integer value

Using sort() function with key as int

lst = ['23', '33', '11', '7', '55']



Output: [‘7′, ’11’, ’23’, ’33’, ’55’]

Sort List in descending order

Using sort() function with key as reverse = ture

mylist = ["BBB", "CC", "AAAA", "DD", "EEEEE"]
mylist.sort(reverse = True)

Output: [‘EEEEE’, ‘DD’, ‘CC’, ‘BBB’, ‘AAAA’]

Do comment if you have any doubts and suggestions on this Python List tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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