0

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.

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

Comments

3

Here is an equivalent function:

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

Note that nresult is created to avoid the problem pointed by JETM.

1 Comment

Thank you! I wish I could accept both of your answers. Very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.