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=[] ?
result, right?for x in resultdoes nothing ifresultis empty.[[]]is not an empty list, hence it does something different.