Computer >> Computer tutorials >  >> Programming >> Python

Convert a list into a tuple in Python.


Sometimes during data analysis using Python, we may need to convert a given list into a tuple. Because some downstream code may be expecting to handle tuple and the current list has the values for that tuple. In this article we will see various ways to do that.

With tuple

This is a straight way of applying the tuple function directly on the list. The list elements get converted to a tuple.

Example

listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = tuple(listA)
# Result
print("The tuple is : ",res)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : ('Mon', 2, 'Tue', 3)

With *

We can apply the * operator we can expand the given list and put the result in a parentheses.

Example

listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = (* listA,)
# Result
print("The tuple is : ",res)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : ('Mon', 2, 'Tue', 3)