Search code examples
pythonpython-itertools

how to iterate using itertools for iterables having different lengths in python?


I have two iterables of different length as follows

  range(5)
  numpy.arange(0,0.3,0.1)

I want to have pairs as follows

    (0,0.)
    (1,0.)
    (2,0.)
    (3,0.)
    (4,0.)

    (0,0.1)
    (1,0.1)
    (2,0.1)
    (3,0.1)
    (4,0.1)

    (0,0.2)
    (1,0.2)
    (2,0.2)
    (3,0.2)
    (4,0.2)

How one could do it using itertools?


Solution

  • Generally a job for itertools.product:

    >>> from itertools import product
    >>> for x in product(range(5), numpy.arange(0, 0.3, 0.1)):
        print x
    ...     
    (0, 0.0)
    (0, 0.10000000000000001)
    (0, 0.20000000000000001)
    (1, 0.0)
    (1, 0.10000000000000001)
    (1, 0.20000000000000001)
    (2, 0.0)
    (2, 0.10000000000000001)
    (2, 0.20000000000000001)
    (3, 0.0)
    (3, 0.10000000000000001)
    (3, 0.20000000000000001)
    (4, 0.0)
    (4, 0.10000000000000001)
    (4, 0.20000000000000001)
    

    Since you want the 'other' order, you could use a comprehension:

    >>> [(x,y) for y in numpy.arange(0, 0.3, 0.1) for x in range(5)]
    
    [(0, 0.0),
     (1, 0.0),
     (2, 0.0),
     (3, 0.0),
     (4, 0.0),
     (0, 0.10000000000000001),
     (1, 0.10000000000000001),
     (2, 0.10000000000000001),
     (3, 0.10000000000000001),
     (4, 0.10000000000000001),
     (0, 0.20000000000000001),
     (1, 0.20000000000000001),
     (2, 0.20000000000000001),
     (3, 0.20000000000000001),
     (4, 0.20000000000000001)]
    

    Or you could reverse the arguments and then reverse each tuple that itertools.product spits out (they always cycle the rightmost element the quickest).

    >>> [x[::-1] for x in product(numpy.arange(0, 0.3, 0.1), range(5))]
    
    [(0, 0.0),
     (1, 0.0),
     (2, 0.0),
     (3, 0.0),
     (4, 0.0),
     (0, 0.10000000000000001),
     (1, 0.10000000000000001),
     (2, 0.10000000000000001),
     (3, 0.10000000000000001),
     (4, 0.10000000000000001),
     (0, 0.20000000000000001),
     (1, 0.20000000000000001),
     (2, 0.20000000000000001),
     (3, 0.20000000000000001),
     (4, 0.20000000000000001)]