How to convert a list to a tuple in Python
How to convert a list to a tuple in Python.
Here's a step-by-step tutorial on how to convert a list to a tuple in Python:
1: Create a list
First, you need to create a list that you want to convert to a tuple. You can create a list by enclosing items in square brackets [] and separating them with commas. For example:
my_list = [1, 2, 3, 4, 5]
2: Use the tuple() function
Python provides a built-in function called tuple()
that can be used to convert a list to a tuple. You can pass your list as an argument to this function, and it will return a tuple containing the same elements as the list. Here's an example:
my_tuple = tuple(my_list)
After executing this code, my_tuple
will contain the converted tuple.
3: Print the tuple
To verify the conversion, you can print the tuple using the print()
function. Here's an example:
print(my_tuple)
This will display the tuple in the output.
Here's the complete code:
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple)
Output:
(1, 2, 3, 4, 5)
Additional Example:
Suppose you have a list with mixed data types, including strings and integers. Here's how you can convert it to a tuple:
my_list = ['apple', 'banana', 1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)
Output:
('apple', 'banana', 1, 2, 3)
That's it! You have successfully converted a list to a tuple using the tuple()
function in Python.