Last modified: Jan 10, 2023 By Alexander Williams
turn a List to a Tuple in python
In this tutorial, we'll learn how to turn or Convert a List into a Tuple in python.
Method 1: using tuple() built-in function
In this following method, we'll use tuple() built-in function to turn a list to a tuple, to understand let's see the syntax and example.
Syntax
# turn a List to a Tuple
tuple(your_list)
Example:
#list
animals = ['cat', 'dog', 'zebra', 'shark']
#turn list to tuple
new_animals = tuple(animals)
#print type of variable
print(type(new_animals))
#print tuple
print(new_animals)
output
<class 'tuple'> ('cat', 'dog', 'zebra', 'shark')
Method 2: using for loop
In this second method, we'll use inline for loop to iterate over the list
syntax
tuple(i for i in yourlist)
Example
#list
animals = ['cat', 'dog', 'zebra', 'shark']
#turn list to tupl
tuple1 = tuple(i for i in animals)
#print type of variable
print(type(tuple1))
#print tuple
print(tuple1)
output
<class 'tuple'> ('cat', 'dog', 'zebra', 'shark')