Search code examples
pythonlistcombinations

Pythonic way of finding ways of walking through consecutive larger and larger lists


List number n contains 0 to n-1

l1 = [0]
l2 = [0,1]
l3 = [0,1,2]

I am looking to find possible combinations of these lists. The example above should yield

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

How would one do this in an efficient and pythonic way.


Solution

  • loop on the lists and also keep a set so that you do not get repeated output

    seen = set()
    l1 = [0]
    l2 = [0,1]
    l3 = [0,1,2]
    for i in l1:
        cur = [str(i)]
        for j in l2:
            cur.append(str(j))
            for k in l3:
                cur.append(str(k))
                seen.add("".join(cur))
                cur.pop()
            cur.pop()
    for i in seen:
        print(i)
    
    

    using itertools

    you can use itertools.product

    import itertools
    l = [[0],[0,1],[0,1,2]]
    
    print(list(itertools.product(*l)))