Convert list to tuple Python

In this article, you’ll see how to convert a list to a tuple in Python. I highly recommend you get the “Python Crash Course Book” to learn Python. There are different methods to convert a list into a tuple. Three methods are given:

Method 1: list to tuple

You can use tuple keyword to convert a list into a tuple. This is a simple and best method.

# Define a list
a = ['DL', 'AI', 5, 10, 'ML']

# Convert the list into tuple
b = tuple(a)

# Display the tuple
print(b)

# Display the type
print(type(b))

Output:

('DL', 'AI', 5, 10, 'ML')
<class 'tuple'>

Method 2

# Define a list
a = ['DL', 'AI', 5, 10, 'ML']

# Convert the list into tuple
b = (*a,)

# Display the tuple
print(b)

# Display the type
print(type(b))

Output:

('DL', 'AI', 5, 10, 'ML')
<class 'tuple'>

Method 3

# Define a list
a = ['DL', 'AI', 5, 10, 'ML']

# Convert the list into tuple
b = tuple(i for i in a)

# Display the tuple
print(b)

# Display the type
print(type(b))

Output:

('DL', 'AI', 5, 10, 'ML')
<class 'tuple'>

Leave a Comment

Your email address will not be published.