Python | Convert a list into a tuple
Given a list, write a Python program to convert the given list into a 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 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)) |
(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)) |
(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)) |
(1, 2, 3, 4)
Recommended Posts:
- Python | Convert mixed data types tuple list to string list
- Python | Convert Integral list to tuple list
- Python | Convert list to indexed tuple list
- Python | Convert list of tuple into dictionary
- Python | Convert a list into tuple of lists
- Python | Convert String to tuple list
- Python | Sort tuple list by Nth element of tuple
- Python | Convert Tuple to integer
- Python | Convert String to Tuple
- Python | Convert tuple to float value
- Python | Convert location coordinates to tuple
- Python | Program to convert a tuple to a string
- Python | Convert String to N chunks tuple
- Python | Convert tuple records to single string
- Python | Convert tuple to adjacent pair dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : ManasChhabra2


