0

I came across following snippet (and could trace its origin to https://docs.python.org/3/library/itertools.html#itertools.product):

def cartesian_product(pools):
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    return result

a_list=[1, 2, 3]
b_list=[4, 5]
all_list=[a_list, b_list]

print (cartesian_product(all_list)) # [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]

If we change the following line:

result = [[]]

to this:

result = []

then code doesn't work.

Now consider the following piece of code where the variable my_list in initialized as my_list=[] and not my_list=[[]] but still we get the expected results:

my_list=[]
my_list.append([1,2])
my_list.append([3,4])
print (my_list) # [[1, 2], [3, 4]]    

So in the function cartesian_product I mentioned above, what is the significance of having result=[[]] and not result=[] ?

2
  • 2
    You did notice that it iterates over result, right? Commented Jul 17, 2017 at 3:59
  • for x in result does nothing if result is empty. [[]] is not an empty list, hence it does something different. Commented Jul 17, 2017 at 4:01

1 Answer 1

5

The list comprehension inside the loop is:

[x+[y] for x in result for y in pool]

This contains the expression x+[y], where x is an element of result. This tries to add an element of result to a list. So each element of result needs to be a list. That is why result is initialized to [[]], which a list with one element, which is a list (an empty list). If you do result = [], there are no elements in result, so the loop will end immediately and do nothing.

Your second example is different because you don't do anything with the elements of my_list. You just add new elements. Also, you don't iterate over the list, so there's no requirement that it contain anything.

There's nothing special about [[]]. It's just that the particular operations that cartesian_product is doing require it to operate on a list of lists. Similarly if you were to write a function that takes, say, the mean of the elements in a list, you'd need to ensure the list has numbers in it (so it makes sense to add them) and is nonempty (since otherwise you'd be dividing by zero when trying to find the mean).

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

Comments

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.