Appearance
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:
Convert a list to a tuple using tuple()
python
# 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)
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
You can also use a generator expression to convert each inner list to a tuple:
Convert a list of lists using a generator expression
python
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 tuple() works on any iterable, not just lists. Once a tuple is created, its elements cannot be modified (tuples are immutable).