5

I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?

for id, elements in enumerate(itertools.izip(as, bs)):
  a = elements[0]
  b = elements[1]
  # do something with id, a and b

Thank you.

Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
Nikolay Vyahhi
  • 1,432
  • 1
  • 16
  • 30

2 Answers2

18

You can assign a and b during the for loop:

for id, (a, b) in enumerate(itertools.izip(as, bs)):
  # do something with id, a and b
Peter Collingridge
  • 10,849
  • 3
  • 44
  • 61
12

You could use itertools.count instead of enumerate:

for id_, a, b in itertools.izip(itertools.count(), as_, bs):
  # do something with id_, a and b

Note that I've changed the variable names slightly to avoid a reserved word and the name of a builtin.

Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
  • 1
    Nice change of variable names in accordance with PEP-8, bu using `itertools.count` over `enumerate` is not actually an improvement. – jamylak Jun 23 '13 at 10:52
  • IMHO it is an improvement, because you can use the `itertools.izip(itertools.count(), as_, bs)` experssion as an argument of `multiprocessing.pool.map_async()`, which is not convenient with the for loop. – user1898037 Jul 26 '17 at 14:28