Python | How to sort a list of strings

Given a list of strings, the task is to sort that list based on given requirement.

There are multiple scenarios possible while sorting a list of sting, like –

  • Sorting in alphabetical/reverse order.
  • Based on length of string character
  • Sorting the integer values in list of string etc.

Let’s discuss various ways to perform this task.

Example #1: Using sort() function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort a list of strings
  
lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks']
  
# Using sort() function
lst.sort()
  
print(lst)

chevron_right


Output:

['a', 'for', 'geeks', 'gfg', 'is', 'portal']

 
Example #2: Using sorted() function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort a list of strings
  
lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks']
  
# Using sorted() function
for ele in sorted(lst):
    print(ele)

chevron_right


Output:

a
for
geeks
gfg
is
portal

 
Example #3: Sort by length of strings

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort a list of strings
  
lst = ['Geeksforgeeks', 'is', 'a', 'portal', 'for', 'geeks']
  
# Using sort() function with key as len
lst.sort(key = len)
  
print(lst)

chevron_right


Output:

['a', 'is', 'for', 'geeks', 'portal', 'Geeksforgeeks']

 
Example #4: Sort string by integer value

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort a list of strings
  
lst = ['23', '33', '11', '7', '55']
  
# Using sort() function with key as int
lst.sort(key = int)
  
print(lst)

chevron_right


Output:

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

Example #5: Sort in descending order

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort a list of strings
  
lst = ['gfg', 'is', 'a', 'portal', 'for', 'geeks']
  
# Using sort() function
lst.sort(reverse = True)
  
print(lst)

chevron_right


Output:

['portal', 'is', 'gfg', 'geeks', 'for', 'a']


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.