Given a list, write a Python program to convert the given list into a Python tuple.
Examples:
Input : [1, 2, 3, 4]
Output : (1, 2, 3, 4)
Input : ['a', 'b', 'c']
Output : ('a', 'b', 'c')
Convert a list into a tuple using tuple()
Using tuple(list_name). Typecasting to tuple can be done by simply using tuple(list_name).
Python3
def convert( list ):
return tuple ( list )
list = [ 1 , 2 , 3 , 4 ]
print (convert( list ))
|
Time complexity: O(n)
Auxiliary space: O(n)
A small variation to the above approach is to use a loop inside tuple() .
Python3
def convert( list ):
return tuple (i for i in list )
list = [ 1 , 2 , 3 , 4 ]
print (convert( list ))
|
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as a new tuple is created to store the converted elements of the list
Convert a list into a tuple Using *list
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
def convert( list ):
return ( * list , )
list = [ 1 , 2 , 3 , 4 ]
print (convert( list ))
|
Convert a list into a tuple Using map and lambda
This program uses the map() function and lambda to convert a list of integers to a list of strings, and then uses the join() method to concatenate the strings in the list with a comma separator.
Approach:
1. Create a list of integers [1, 2, 3, 4].
2. Use the map() function and lambda to convert each integer in the list to its corresponding string representation, resulting in a list of strings [‘1’, ‘2’, ‘3’, ‘4’].
3. Use the join() method to concatenate the strings in the list with a comma separator, resulting in a single string ‘1,2,3,4’.
4. Print the final string as the output.
Python3
strings_list = list ( map ( lambda x: str (x),
[ 1 , 2 , 3 , 4 ]))
output_str = "," .join(strings_list)
print (output_str)
|
Convert a list into a tuple without Using builtin function
Here we are not going to use any function for typecasting.
Python3
def convert_list_to_tuple(lst):
tuple_result = ()
for element in lst:
tuple_result + = (element,)
return tuple_result
my_list = [ 1 , 2 , 3 , 4 ]
my_tuple = convert_list_to_tuple(my_list)
print (my_tuple)
|
Output:
(1, 2, 3, 4)