Lists
How to convert a list to a tuple in Python
Quick answer
Use tuple() function or the tuple() constructor to convert a list to a tuple in Python, like tuple([1, 2, 3]).
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)The snippet converts a list to a tuple using the tuple() function. This approach wins because it is straightforward and efficient. However, be aware that this creates a new tuple object, it does not modify the original list.
The tuple() function works by iterating over the input iterable, in this case a list, and creating a new tuple containing all the elements.
Variations
Alternate approach
my_list = [1, 2, 3]
my_tuple = (*my_list,)
print(my_tuple)using unpacking
Edge case
my_list = [[1], [2], [3]]
my_tuple = tuple(map(tuple, my_list))
print(my_tuple)for nested lists
Related pattern
my_set = {1, 2, 3}
my_tuple = tuple(my_set)
print(my_tuple)converting set to tuple
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.