In this tutorial, we will see how to convert list to tuple.
[toc]
Using tuple function
You can use python tuple() function to convert list to tuole.It is simplest way to convert list to tuple.
Let’s understand with the help of example.
listOfFruits=['Apple','Orange','Grapes','Banana']
print("List of Fruits",listOfFruits)
tupleOfFruits=tuple(listOfFruits)
print("Tuple of Fruits:",tupleOfFruits)
Output:
List of Fruits [‘Apple’, ‘Orange’, ‘Grapes’, ‘Banana’]
Tuple of Fruits: (‘Apple’, ‘Orange’, ‘Grapes’, ‘Banana’)
Tuple of Fruits: (‘Apple’, ‘Orange’, ‘Grapes’, ‘Banana’)
As you can see, tuple starts with open bracket and ends with close bracket.
Using *list,
There is another way to convert list to tuple in python>=3.5 version.This approach is bit faster than tuple function.
This will unpack list into tuple literal and it will be created due to , at the end.
listOfFruits=['Apple','Orange','Grapes','Banana']
print("List of Fruits",listOfFruits)
tupleOfFruits=*listOfFruits,
print("Tuple of Fruits:",tupleOfFruits)
Output:
List of Fruits [‘Apple’, ‘Orange’, ‘Grapes’, ‘Banana’]
Tuple of Fruits: (‘Apple’, ‘Orange’, ‘Grapes’, ‘Banana’)
Tuple of Fruits: (‘Apple’, ‘Orange’, ‘Grapes’, ‘Banana’)
That’s all about how to convert list to tuple in python.