Change language

Python | Sort all sublists in a given list of strings

| |

Example :

  Input:  lst = [[’Machine’,’ London’, ’Canada’,’ France’], [ ’Spain’,’ Munich’], [’Australia’,’ Mandi’]]  Output:  flist = [[’Canada’,’ France’, ’London’,’ Machine’], [ ’Munich’,’ Spain’], [’Australia’,’ Mandi’]] 

There are several ways to sort each list alphabetically.

Method # 1: Map Usage

# Python code to sort all sublists
# in this list of strings

 
# Initialization list

Input = [[ ’Machine’ , ’ London’ , ’Canada’ , ’ France’ , ’ Lanka’ ],

[ ’ Spain’ , ’Munich’ ],

  [ ’Australia’ , ’ Mandi’ ]]

 
# Using the map for sorting

Output = list ( map ( sorted , Input ))

 
# Printout

print (Output)

Exit:

[[’Canada ’,’ France ’,’ Lanka ’,’ London ’,’ Machine ’], [’ Munich ’,’ Spain ’], [’ Australia ’,’ Mandi ’]]

Method # 2: Using lambda and sorting

# Python code to sort all sublists
# in this list of strings

 
# Initialization list

Input = [[ ’Machine’ , ’ London’ , ’Canada’ , ’France’ , ’Lanka’ ],

  [ ’Spain’ , ’ Munich’ ],

[ ’ Australia’ , ’Mandi’ ]]

 
# using lambda and sorted

Output = [ sorted (x, key = lambda x: x [ 0 ]) for x in Input ]

 
# Printout

print (Output)

Exit:

[ [’Canada’, ’France’, ’London’, ’Lanka’, ’Machine’], [’Munich’, ’Spain’], [’Australia’, ’Mandi’]]

Method # 3: Using iteration and sorting

# Python code to sort all sublists
# in this list of lines

  
# Initialization list

Input = [[ ’Machine’ , ’London’ , ’ Canada’ , ’ France’ , ’Lanka’ ],

[ ’Spain’ , ’ Munich’ ] ,

[ ’Australia’ , ’Mandi’ ]]

 
# with Sublist editing

for sublist in Input :

sublist.sort ()

 
# Output to print

print ( Input )

Output:

[[’Canada’, ’France’, ’Lanka’, ’London’, ’Machine’], [’Munich’, ’Spain’], [’Australia’, ’Mandi ’]]

Python | Sort all sublists in a given list of strings Python functions: Questions

Python | Sort all sublists in a given 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