4 ways to convert list to tuple in Python

Tuple Python

In this article, we are going to learn 4 ways to convert list to a 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 list to a tuple. It takes an iterable as an argument We pass a list iterable as an argument to tuple() to convert 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. Convert Mutiple Lists to Python tuple


In this example, we will convert two or multiple lists in tuples by using the zip() function. It creates nested tuple from both lists. We will use two lists and then by using 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. Loop over the elements of 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 pass the list into () parenthesis and unpack 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 any of them as per requirement.