Search code examples
pythonpython-itertools

Itertools Python


Is there any way to use itertools product function where the function returns each combination of lists step by step ?

For example: itertools.product(*mylist) -> the solution should return the first combination of the lists , after that the second one etc.


Solution

  • As @ggorlen has explained, itertools.product(...) returns an iterator. For example, if you have

    import itertools
    mylist = [('Hello','Hi'),('Andy','Betty')]
    iterator = itertools.product(*mylist)
    

    next(iterator) or iterator.__next__() will evaluate to 'Hello Andy' the first time you call them, for example. When you next call next(iterator), it will return 'Hello Betty', then 'Hi Andy', and finally 'Hi Betty', before raising StopIteration errors.

    You can also convert an iterator into a list with list(iterator), if you are more comfortable with a list, but if you just need the first few values and mylist is big, this would be really inefficient, and it might be worth the time familiarising yourself with iterators.

    Do consider whether you are really just iterating through iterator though. If so, just use

    for combination in iterator:
        pass # Body of loop
    

    Even if you just need the first n elements and n is large you can use

    for combination in itertools.islice(iterator, n):
        pass # Body of loop