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.
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))
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.