Multiply values in 3 lists or more

Hi I am trying to multiply every value with every other value in these three lists. It works, but this way I end up adding for loops if I get more lists. I assume there must be something smarter. Please let me know.

# Load the Python Standard and DesignScript Libraries
import sys
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN

# Place your code below this line
testx = [1,2,3]
testy = [2,3,4]
testz = [3,4,5]

Result = []

for x in testx:
	for y in testy:
		for z in testz:
			Temp = x * y * z
			Result.append(Temp)

# Assign your output to the OUT variable.
OUT = Result

Hi Daniel,

itertools has the product function. See the ironpython documentation to it.
functools has the reduce function. See the ironpython documentation to it.

from functools import reduce 
from itertools import product
test_list = [testx, testy, testz]
for combi in product(*test_list):
	result1 = reduce((lambda x, y: x * y), combi)
	Result.append(result1)

The * before a list unpacks it. Technically you could write product(testx, testy, testz). It will just be easier for you to unpack a list, instead of typing it out every time you have a new list. (e.g. product(*test_list)

reduce takes a function and reduces the given list by applying it on each item.
In this case the function is a lambda function that multiplies 2 values

4 Likes