Sometimes, we want to unpack tuples in for loops with Python.
In this article, we’ll look at how to unpack tuples in for loops with Python.
How to unpack tuples in for loops with Python?
To unpack tuples in for loops with Python, we separate the tuple entries with commas.
For instance, we write:
x = [(1, 2), (3, 4), (5, 6)]
for a, b in x:
print(a, b)
We have the list x
which is a list of tuples.
Then we loop through each entry in x
and unpack the tuples entry with a, b
.
In the loop body, we print out the tuple entries.
And so we get:
1 2
3 4
5 6
printed.
Conclusion
To unpack tuples in for loops with Python, we separate the tuple entries with commas.