Python - Tuple assignment in for loops


When iterating through a sequence of tuples, the loop target itself can actually be a tuple of targets.


T = [(1, 2), (3, 4), (5, 6)] 
for (a, b) in T:                   # Tuple assignment at work 
     print(a, b)


Here, the first time through the loop is like writing (a,b) = (1,2), the second time is like writing (a,b) = (3,4), and so on.

It will automatically unpack the current tuple on each iteration.

Related Example