Lesson 05
Tuple Comprehension? — Generators and tuple()
Parentheses around a for clause create a Python generator, not a tuple. Inspect the type, then convert with tuple() to get a real tuple.
What you will learn
- Why
(expr for name in iterable)is not a tuple comprehension - The type is
generator - How
tuple(generator)builds a real tuple - How this differs from list and set comprehensions
This continues from Dict comprehension. Tuples: tuple data type.
The big idea
It is natural to write parentheses and expect a tuple, because lists use [ ] and sets use { }.
x = (int(val) for val in raw.split())The teaching program names this clearly: feeling that it is tuple comprehension — here x is a generator.
raw = "10 2 22 50"
x = (int(val) for val in raw.split())
print(type(x))
t = tuple(x)
print("Elements in tuple=", t)
print(type(t))Output shape:
<class 'generator'>
Elements in tuple= (10, 2, 22, 50)
<class 'tuple'>Why a generator?
A generator is lazy. It does not build the whole tuple in memory until you consume it (tuple(x), list(x), or a for loop).
Consume it once:
x = (int(val) for val in "1 2 3".split())
print(tuple(x))
print(tuple(x)) # empty — already consumedThe second tuple(x) is ().
Compare brackets
| Brackets | Name | Type |
|---|---|---|
[x for x in data] |
List comprehension | list |
{x for x in data} |
Set comprehension | set |
{k: v for ...} |
Dict comprehension | dict |
(x for x in data) |
Generator expression | generator |
To get a tuple in one extra step: tuple(x for x in data).
t = tuple(int(val) for val in "10 2 22".split())
print(t, type(t))That is the usual interview answer: there is no tuple comprehension; use a generator expression plus tuple().
Classroom vs playground
print("Enter List of Values separated by space:")
x = (int(val) for val in input().split())
t = tuple(x)Playground: replace input() with a string, keep the generator and tuple() cast.
Common mistakes
Printing the generator — you see <generator object ...>, not the numbers.
Calling tuple(x) twice — the generator is exhausted after the first conversion.
Using [ ] when you wanted a tuple — that builds a list; wrap with tuple(...) if you need a tuple.
Interview cheat sheet
| Question | Answer |
|---|---|
| Tuple comprehension? | Does not exist |
(x for x in data) |
Generator expression |
| Make a tuple | tuple(...) |
| List of the same idea | [x for x in data] |
Practice in the playground
- Print
xbeforetuple(x)and read the generator type. - Call
tuple(x)a second time — expect(). - Build
tuple(v * 2 for v in (1, 2, 3))and confirm(2, 4, 6).
Back to the Comprehensions overview.
Loading playground…
Check your understanding
Tuple and generator quiz
Does Python have a true tuple comprehension that returns a tuple immediately?
1 / 10