1

I was just looking through the itertools documentation, looking for a way to get rid of a nested for loop like this:

for a in b:
    for c in b:
        <statement>

However, I couldn't find anything. Is there not a function for this? Should I just keep the nested loops?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
LazySloth13
  • 2,369
  • 8
  • 28
  • 37
  • 4
    `for a, c in itertools.product(b, repeat=2): …` – millimoose Oct 28 '13 at 13:12
  • 2
    or `itertools.product(b, repeat=2)`. – Martijn Pieters Oct 28 '13 at 13:13
  • 1
    The original question seems to have been using `for c in b:` in the second line. Several answers seem to apply to that. Maybe if a change of the question changes its meaning so drastically, SO should implement a way of handling this. – Alfe Oct 28 '13 at 14:01
  • Rolled back to the original version as it changes the meaning of the question drastically http://meta.stackexchange.com/a/106812/235416 – thefourtheye Oct 29 '13 at 09:55

2 Answers2

4

Yes there is. Its called itertools.product

For example:

import itertools

for item in itertools.product([0, 1], repeat = 2):
    print item

Output

(0, 0)
(0, 1)
(1, 0)
(1, 1)

It is equivalent to

b = [0, 1]
for a in b:
    for c in b:
        print (a, c)
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
4

You can use chain.from iterable:

from itertools import chain

b = [[1, 2, 3], [4, 5, 6]]

for i in chain.from_iterable(b):
    print i

Ideally, b has all the values. So this translates to:

for a in b:
    for c in a:
        print c

Working example. What you're really trying to do is flatten a list, and thats actually included in the recipes for itertools.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199