How to Create a Tuple in Python: Syntax and Examples
In Python, you create a tuple by placing items inside
( ) separated by commas, like my_tuple = (1, 2, 3). You can also create a tuple without parentheses by just separating values with commas, for example, my_tuple = 1, 2, 3.Syntax
A tuple is created by placing values separated by commas inside parentheses ( ). Parentheses are optional but recommended for clarity. A single-item tuple must have a trailing comma to distinguish it from a regular value.
- Multiple items:
my_tuple = (1, 2, 3) - Without parentheses:
my_tuple = 1, 2, 3 - Single item tuple:
my_tuple = (1,)(note the comma)
python
my_tuple = (1, 2, 3) single_item = (1,) no_parentheses = 4, 5, 6
Example
This example shows how to create tuples with multiple items, a single item, and without parentheses. It also prints each tuple to show their contents.
python
my_tuple = (10, 20, 30) single_item = (100,) no_parentheses = 'a', 'b', 'c' print(my_tuple) print(single_item) print(no_parentheses)
Output
(10, 20, 30)
(100,)
('a', 'b', 'c')
Common Pitfalls
One common mistake is forgetting the comma for a single-item tuple, which makes it just a value in parentheses, not a tuple. Another is confusing tuples with lists; tuples are immutable, so you cannot change their items after creation.
python
not_a_tuple = (5) # This is just the number 5, not a tuple correct_tuple = (5,) print(type(not_a_tuple)) # Output: <class 'int'> print(type(correct_tuple)) # Output: <class 'tuple'>
Output
<class 'int'>
<class 'tuple'>
Quick Reference
| Syntax | Description |
|---|---|
| (1, 2, 3) | Tuple with multiple items |
| 1, 2, 3 | Tuple without parentheses |
| (1,) | Single-item tuple (comma required) |
| () | Empty tuple |
Key Takeaways
Create tuples by placing comma-separated values inside parentheses.
Use a trailing comma for single-item tuples to distinguish them from regular values.
Tuples are immutable; you cannot change their contents after creation.
Parentheses are optional but improve code readability.
Empty tuples are created with empty parentheses: ().