Concept Flow - Single-element tuple
Start with value
Add comma after value?
Yes No
Create tuple
Result: tuple
This flow shows how adding a comma after a single value creates a tuple, otherwise it remains just the value.
Jump into concepts and practice - no test required
a = (5,) b = (5) print(type(a)) print(type(b))
| Step | Code Line | Action | Value/Type |
|---|---|---|---|
| 1 | a = (5,) | Create single-element tuple with comma | a = (5,), type: tuple |
| 2 | b = (5) | Create value in parentheses without comma | b = 5, type: int |
| 3 | print(type(a)) | Print type of a | <class 'tuple'> |
| 4 | print(type(b)) | Print type of b | <class 'int'> |
| 5 | End | No more code | Execution stops |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| a | undefined | (5,) | (5,) | (5,) |
| b | undefined | undefined | 5 | 5 |
Single-element tuple syntax: Use a comma after the single value inside parentheses: (value,) Without comma, parentheses just group the value: (value) Comma is required to create a tuple with one item Example: a = (5,) is a tuple, b = (5) is int
Which of the following is a correct way to create a single-element tuple with the number 5?
(5,) uses (5,) which is the correct single-element tuple syntax. (5) is just the number 5 in parentheses, not a tuple. [5] is a list, and {5} is a set.Which of the following code snippets will NOT create a tuple?
A) t = (7,)
B) t = (7)
C) t = 7,
D) t = (7, 8)What is the output of the following code?
t = (42)
print(type(t))
t2 = (42,)
print(type(t2))Find the error in this code snippet:
my_tuple = ("hello")
print(type(my_tuple))You want to create a tuple that contains a single list [1, 2, 3]. Which of the following will correctly create a single-element tuple containing that list?
t = ([1, 2, 3]) is just the list in parentheses, so t is a list. t = ([1, 2, 3],) has the list inside parentheses with a comma, making it a single-element tuple. t = [1, 2, 3] is just a list. t = ([1, 2, 3], [4, 5]) is a tuple with two lists.