Python list to tuple | Conversion example code

Using the tuple() function you can easily convert the list into a tuple in Python. Other ways are using a loop inside the tuple or Unpack list inside the parenthesis.

tuple(list_name)

Python list to a tuple examples

Simple example code in different ways.

Using tuple() builtin function

Pass the entire list as a parameter within the tuple() function.

my_list = ['A', 'B', 'C']

tuple1 = tuple(my_list)

print(tuple1)
print(type(tuple1))

Output:

Python list to tuple

Using loop inside the tuple

Use a loop inside the built-in function tuple().

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

tuple1 = tuple(i for i in my_list)
print(tuple1)

Output: (1, 2, 3, 4, 5)

Unpack list inside the parenthesis

This method is faster in comparison to others, but it suffers from readability which is not efficient enough.

my_list = [1, 2, 3, 'A', 'B']

tuple1 = (*my_list,)

print(tuple1)

Output: (1, 2, 3, ‘A’, ‘B’)

Do comment if you have any doubts and suggestions on this Python list tuple topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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