1

Given two lists a=[(1,11), (2,22), (3,33)] and b=[111, 222, 333] I would like to know if there is a syntactically easy-to-read solution to iterate over triples of values as follows:

for x,y,z in WANTED(a, b):
    print(x, y, z)

# should iterate over (1,11,111), (2,22,222), (3,33,333)

I do know that this can be done like

for _item, z in zip(a, b):
    x, y = _item
    print(x, y, z)

and I also do know how to pack this into my own custom iterator, but I'd like to know if this is possible using low level built-in solutions (maybe itertools) to achieve this with syntactically easy-to-read code.

flonk
  • 3,726
  • 3
  • 24
  • 37

1 Answers1

1

If I understand you correctly, you can do:

a = [(1, 11), (2, 22), (3, 33)]
b = [111, 222, 333]

for (x, y), z in zip(a, b):  # <-- note the (x, y)
    print(x, y, z)

This prints:

1 11 111
2 22 222
3 33 333
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Thanks, turned out I was rather missing some basic knownledge on syntax than a "generalization" of some method :) I use this very often now, e.g. it is even more helpful when using `enumerate` with lists of tuples. – flonk Mar 27 '22 at 10:49