Change language

Python | How to sort a list of strings

|

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’] 

Python | How to sort a list of strings Python functions: Questions

Python | How to sort a list of strings String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method