Convert Python List to Tuple with example

In our Previous Python tutorials for beginners, we study about Python list and Python tuples with examples. In this post of Python examples, we will see that how we can convert Python list to Python Tuple. Below is the steps or way to convert list to tuple.

Before proceeding further, let’s see what is Python list and tuple in brief. Both list and tuple are data structure type for storing the elements in Python.

Main difference between list and Tuple is that :

Python lists are mutable where as tuples are immutable.

 

list in Python is defined in square brackets, where are tuples are defined as round brackets ().

example:

# Python list & tuple example

l1=[1,2,3,4,5]

t1=(6,7,8,9,10)

print("l1 is of type",type(l1))
print("t1 is of type",type(t1))

 

Output

l1 is of type <class 'list'>
t1 is of type <class 'tuple'>
  • l1 is list and t1 is tuple

 

Now we will see how we can convert list to tuple in Python.

 

By using tuple() function

By using tuple() function, we convert list to tuple. below is the example

# Python convert list to tuple example

l1=[1,2,3,4,5]

t1=(6,7,8,9,10)

print("l1 is of type",type(l1))
print("t1 is of type",type(t1))

t2=tuple(l1)

print(t2)

print("t2 is of type",type(t2))

 

Output

l1 is of type <class 'list'>
t1 is of type <class 'tuple'>
(1, 2, 3, 4, 5)
t2 is of type <class 'tuple'>

 

  • In our previous example, we have list l1.
  • when we apply tuple() function to list l1, it convert list to tuple
  • we can check the type of t2, which holds the tuple() function result.

 

Hence by using tuple() function we can convert list to tuple.

READ  Python for loop example

 

 

 

 

Please follow and like us: