Convert list to tuple in Python
You can convert a list to a tuple in Python by using the built-in tuple() function. Here's an example:
# Sample list
my_list = [1, 2, 3, 4]
# Convert list to tuple
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3, 4)
Watch a video course
Python - The Practical Guide
You can also use the *
operator to unpack the elements of a list and pass them as arguments to the tuple constructor. This is useful when you have a list of lists and you want to convert each inner list to a tuple.
my_list = [[1,2],[3,4],[5,6]]
my_tuple = tuple(tuple(i) for i in my_list)
print(my_tuple) # Output: ((1, 2), (3, 4), (5, 6))
Another way to do the same is list comprehension with tuple
my_list = [[1,2],[3,4],[5,6]]
my_tuple = tuple([tuple(i) for i in my_list])
print(my_tuple) # Output: ((1, 2), (3, 4), (5, 6))
Note that once a tuple is created, its elements cannot be modified (tuples are immutable).