In this article, we are going to learn 4 ways to convert list to tuple in Python with examples, we are going to use tuple(), zip(), generator, and many more.
1. tuple() to convert List to Python tuple
In this code example, we are using an in-built tuple() method to convert a python list to a tuple. It takes an iterable as an argument We pass a list as an iterable argument to the tuple() method to convert the list into a tuple.
#convert a list to a Python tuple
numlist = [1,2,3,4,5,6,7,8,9]
print('Current list=\n',numlist)
#create a tuple from list item
tuple_of_list = tuple(numlist)
print('tuple from a list =\n',tuple_of_list)
Output
Current list=
[1, 2, 3, 4, 5, 6, 7, 8, 9]
tuple from a list =
(1, 2, 3, 4, 5, 6, 7, 8, 9)
2. How to Convert Mutiple Lists to Python tuple
In this example, we will learn how to convert two or multiple lists into tuples by using the zip() function. It creates a nested tuple from both given lists. We will use two lists and then by using the zip() function we will generate a tuple.Let us understand with the example below:
#convert a list to a Python tuple
numlist = [1,2,3,4,5,6,7,8,9]
numlist1= [10,11,12,13,14,15,16,17,18,19]
print('Current num list=\n',numlist)
print('Current num list1=\n',numlist1)
#create a tuple from list item using zip()
tuple_of_list = tuple(zip(numlist,numlist1))
print('tuple from a list =\n',tuple_of_list)
Output
Current num list=
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Current num list1=
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
tuple from a list =
((1, 10), (2, 11), (3, 12), (4, 13), (5, 14), (6, 15), (7, 16), (8, 17), (9, 18))
3. Convert List to Tuple using generator
In this code snippet, we are using the generator to convert a list to a tuple. We are Loop over the elements of the list and converting it tuple using the tuple() method.
#convert a list to a Python tuple
numlist = [1,2,3,4,5,6,7,8,9]
list_to_tuple = tuple(item for item in numlist)
print('tuple to list =\n',list_to_tuple)
Output
tuple to list =
(1, 2, 3, 4, 5, 6, 7, 8, 9)
4. Unpack list to convert into tuple
We can unpack all elements of a list to the tuple by using the * operator. We will pass the list with * operator inside the into () parenthesis and this will unpack a list to tuple.
#convert a list to a Python tuple
numlist = [1,2,3,4,5,6,7,8,9,1,2,3]
list_to_tuple = (*numlist,)
print('tuple to list =\n',list_to_tuple)
Output
tuple to list =
(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3)
Conclusion
We have explored different 5 ways to convert a list to a Python tuple with code examples. We can do any of them as per requirement.