How to Convert List to Tuple in Python

To convert a list to a tuple in Python, you can use the tuple() function or *list.

Method 1: Using the tuple() function

The tuple() is a built-in function that accepts the list as an argument and returns the tuple. The list elements will not change when it converts into a tuple.

Example

mando = ["Mandalorian", "Grogu", "Ahsoka Tano", "Bo Katan", "Boba Fett"]
print(mando)
print(type(mando))

mando_tuple = tuple(mando)
print(mando_tuple)
print(type(mando_tuple))

Output

['Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett']
<class 'list'>
('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett')
<class 'tuple'>

In this example, we have defined a list and checked its data type. To check the data type in Python, use the type() method.

Then use the tuple() method and pass the list to that method, and it returns the tuple containing all the list elements.

Method 2: Using the (*list, )

From Python >= 3.5, you can make this easy approach that will create a conversion from the list to a tuple is (*list, ). The (*list, ) unpacks the list inside a tuple literal, created due to the single comma’s presence (, ).

Example

mando = ["Mandalorian", "Grogu", "Ahsoka Tano", "Bo Katan", "Boba Fett"]
print(mando)
print(type(mando))

mando_tuple = (*mando, )
print(mando_tuple)
print(type(mando_tuple))

Output

['Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett']
<class 'list'>
('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett')
<class 'tuple'>

You can see that (*mando, ) returns the tuple containing all the list elements. Never use variable names like tuple, list, dictionaryor set to improve your code readability.

Sometimes, it will create confusion. Don’t use the reserved keywords while giving the variable a name.

In Python 2.x, if you’ve redefined the tuple to be a tuple rather than the type tuple by mistake, it will give you the following error.

TypeError: ‘tuple’ object is not callable

But, if you use Python 3.x or the latest version, you will not get any errors.

mando = ("Mandalorian", "Grogu", "Ahsoka Tano", "Bo Katan", "Boba Fett")
print(mando)

mando_tuple = tuple(mando)
print(mando_tuple)

Output

('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett')
('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett')

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.