Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Convert a list into a tuple

  • Difficulty Level : Basic
  • Last Updated : 22 Jul, 2019

Given a list, write a Python program to convert the given list into a tuple.

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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 tuple can be done by simply using tuple(list_name).




# Python3 program to convert a 
# list into a tuple
def convert(list):
    return tuple(list)
  
# Driver function
list = [1, 2, 3, 4]
print(convert(list))
Output:
(1, 2, 3, 4)

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




# Python3 program to convert a 
# list into a tuple
def convert(list):
    return tuple(i for i in list)
  
# Driver function
list = [1, 2, 3, 4]
print(convert(list))
Output:
(1, 2, 3, 4)

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




# Python3 program to convert a 
# list into a tuple
def convert(list):
    return (*list, )
  
# Driver function
list = [1, 2, 3, 4]
print(convert(list))
Output:
(1, 2, 3, 4)



My Personal Notes arrow_drop_up
Recommended Articles
Page :