Python | How to sort a list of strings

Python Methods and Functions | String Variables

There are several possible scenarios for sorting the list of bites, for example:

  • Sort alphabetically / in reverse order.
  • Based on string character length
  • Sorting integer values ​​in a list of strings, etc.

Let's discuss the different ways to accomplish this task.

Example # 1: Using the function sort () .

# Python program for sorting a list of strings

 

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

 
# Using the sort () function
lst.sort ()

 

print (lst)

Output:

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

Example # 2: Using the sorted () function.

# Python program for sorting a list of strings

 

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

  
# Using the sorted () function

for ele in sorted (lst):

print (ele)

Exit :

 a for geeks gfg is portal 

Example # 3: sorting by line length

# Python program for row list editing

 

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

 
# Using the sort () function with the key as len

lst.sort (key = len )

 

print ( lst)

  Exit :

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

Example # 4: Sorting a row by integer

# Python program for sorting a list of strings

 

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

 
# Using the sort () function with key as int

lst.sort (key = int )

 

print (lst)

Exit:

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

Example # 5: descending sort

# Python string list sorting program

 

lst = [ 'gfg' , ' is' , 'a' , ' portal' , 'for' , 'ge eks' ]

 
# Using the sort () function

lst.sort (reverse = True )

 

print (lst)

Exit :

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




Get Solution for free from DataCamp guru