I have two iterables, and I want to go over them in pairs:
foo = [1, 2, 3]
bar = [4, 5, 6]
for (f, b) in iterate_together(foo, bar):
print("f:", f, " | b:", b)
That should result in:
f: 1 | b: 4
f: 2 | b: 5
f: 3 | b: 6
One way to do it is to iterate over the indices:
for i in range(len(foo)):
print("f:", foo[i], " | b:", bar[i])
But that seems somewhat unpythonic to me. Is there a better way to do it?
Related tasks:
* How to merge lists into a list of tuples? - given the above foo
and bar
, create the list [(1, 4), (2, 5), (3, 6)]
.
* How can I make a dictionary (dict) from separate lists of keys and values? - create the dict {1: 4, 2: 5, 3: 6}
.
* Create a dictionary with comprehension - constructing dict
using zip
in a dict comprehension.