+

Python | Convert list to tuple

Examples :

  Input:  [1, 2, 3, 4]  Output:  (1, 2 , 3, 4)  Input:  [`a`,` b`, `c`]  Output:  (` a`, `b`,` c`)  

Approach # 1 Using tuple (list_name) .

Typecasting to a tuple can be done simply with the tuple (list_name) .

# Python3 conversion program
# list in tuple

def convert ( list ):

  return tuple ( list )

 
# Driver function

list = [ 1 , 2 , 3 , 4 ]

print (convert ( list ))

Exit:

 (1, 2, 3, 4) 

Approach # 2:
A small variation on the above approach is to use a loop inside tuple () .

# Python3 conversion program
# list in tuple

def convert ( list ):

return tuple (i for i in list )

 
# Driver function

list = [ 1 , 2 , 3 , 4 ]

print (convert ( list  ))

Exit:

 ( 1, 2, 3, 4) 

Approach # 3: Using (* list,)
This essentially unpacks a list l inside a tuple literal that is created due to the presence of a single comma (,). This approach is slightly faster, but suffers from readability.

# Python3 conversion program
# list in tuple

def convert ( list ):

return ( * list ,)

 
# Driver function

list = [ 1 , 2 , 3 , 4 ]

print (convert ( list ))

Exit:

 (1, 2, 3, 4)                                        
             
                
Get Solution for free from DataCamp guru