0

This is my implementation:

def walk_two(a, b):
    for x in a:
        for y in b:
            yield x, y

a = xrange(2)
b = xrange(3)

for x, y in walk_two(a, b):
    print x, y

With this output:

0 0
0 1
0 2
1 0
1 1
1 2

Is there a better (more pythonic) way of doing that? A built-in? A more generic walkN?

blueFast
  • 41,341
  • 63
  • 198
  • 344

4 Answers4

7

You are looking for itertools.product:

from itertools import product
a = xrange(2)
b = xrange(3)

for x, y in product(a, b):
    print x, y
Daniel
  • 42,087
  • 4
  • 55
  • 81
3

itertools.product does what you want and is extensible to more lists:

https://docs.python.org/2/library/itertools.html#itertools.product

import itertools
a = xrange(2)
b = xrange(3)

for x, y in itertools.product(a, b):
    print x, y

Output:

0 0
0 1
0 2
1 0
1 1
1 2
sebastian
  • 9,526
  • 26
  • 54
1

Have a look at itertools.product.

Antoine
  • 1,070
  • 7
  • 11
0

I think this one is slightly better:

>>> for a in xrange(2):
...   for b in xrange(3):
...     print a, b
... 
0 0
0 1
0 2
1 0
1 1
1 2

You don't need to use the generator here, as you are using the xrange() function. The function returns xrange object instead of a list.

>>> a = xrange(10)
>>> a
xrange(10)
>>> 
Tamim Shahriar
  • 739
  • 4
  • 9
  • Not the more pythonic but this code is the fastest one. – xbello Aug 08 '14 at 08:11
  • In my case, performance is not a worry, readability is. Having a single loop instead of two, improves readability drastically. Having a single loop instead of N (for the general case), makes wonders for readability. – blueFast Aug 08 '14 at 08:14
  • @jeckyll2hide, this answer was being downvoted. Yeah, it's awful to nest many *for loops*, but if someone stumbles into this question with only two lists to iterate and performance is a worry... use this solution! No need to downvote. – xbello Aug 08 '14 at 15:10
  • @xbello: I didn't downvote, but I should have. The answer here is the same as the code in my question. – blueFast Aug 09 '14 at 08:30
  • The answer here is not exactly the same as in your question. You didn't need to use the walk_two method. Is it unnecessary here. – Tamim Shahriar Aug 09 '14 at 16:45