search

How to convert a list to a tuple in Python?

To convert a list to a tuple in Python, you can use the tuple() function. Here's an example:

my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple)  # Output: (1, 2, 3, 4, 5)

In the above example, the tuple() function is used to convert the list my_list to a tuple. The resulting tuple contains the same elements as the original list.

The tuple() function takes an iterable (such as a list) as an argument and returns a new tuple containing the elements of the iterable. In this case, we pass the list my_list to the tuple() function, which converts each element of the list into a separate element in the resulting tuple.

After conversion, you can use the resulting tuple as a regular tuple in Python. Note that the resulting tuple is immutable, meaning its elements cannot be modified once the tuple is created.

Keep in mind that the conversion from a list to a tuple creates a new tuple object. If you modify the original list after the conversion, it will not affect the converted tuple.

Related Questions You Might Be Interested