How to Create a Tuple in Python
To create a tuple in Python, you can use () parentheses or the tuple() function to create a tuple from a list.
The following examples show how to create a tuple in Python using two different methods.
Using () Parentheses
We can use () parentheses to create a tuple.
Suppose we have the following data:
# Create empty tuple
tuple_ = ()
# Add elements to tuple
tuple_ = (1, 2, 3, 4, 5, 6)
# Show tuple
print(tuple_)
Output: 👇️
(1, 2, 3, 4, 5, 6)
In this example, we first create an empty tuple tuple_ and then add elements to it. The output shows the tuple created using () parentheses.
Using tuple() Function
We can use the tuple() function to create a tuple from a list.
Suppose we have the following data:
# Create list
list1 = [1, 2, 3, "A", "B"]
# Create tuple from list
tuple_ = tuple(list1)
# Show tuple
print(tuple_)
Output: 👇️
(1, 2, 3, 'A', 'B')
In this example, we use the tuple() function to create a tuple tuple_ from the list list1.
The output shows the tuple created from the list using the tuple() function.
Conclusion
We can use () parentheses or the tuple() function to create a tuple in Python.