Search code examples
pythonfor-loopnested-loops

Convert this single-line nested for loop to multi-line in python


I am having trouble understanding what the difference is in the code I am modifying here. The first section is right from python documentation.

def product(*args, **kwds):
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

I wanted to make a very similar piece of code but have conditions on when we actually take the product for specific elements in the arguments, so I wanted to convert the line result = [x+[y] for x in result for y in pool] into multiple lines, then I could use my if statements and such. Here is what I did, but when I run it, it seems to get stuck in an infinite loop, or something...

def Myproduct(*args, **kwds):
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        for x in result:
            for y in pool:
                result.append(x+[y])
    for prod in result:
        yield tuple(prod)

I would like to actually understand the difference here. I have read through and think I get this post, but still I am not seeing how to properly convert in this case, or why it is not the same conversion at least. Thank you in advance.


Solution

  • The problem is that you're adding to the list that you're iterating over. So if at first, result = [[]] and pools = [1, 2, 3], then after the first iteration over for x in result, your list will be [[], [] + [1]], so then you'll grab the second element, etc.

    The list comprehension is creating a new list in one line, and then renaming it to map to result.

    Be very careful about modifying lists you're iterating over!