Calculating the Product of Elements in a List
In this section, we will define a list of numbers and compute the product of its elements.
Example
Input:
list1 = [1, 2, 3]
Output:
6
Calculation:
1 * 2 * 3 = 6
Example 1: Using a Loop
def multiplyList(myList): result = 1 for x in myList: result *= x return result list1 = [1, 2, 3] list2 = [3, 2, 4] print(multiplyList(list1)) # Output: 6 print(multiplyList(list2)) # Output: 24
Output:
6 24
In this example, we use a for
loop to iterate through the list and calculate the product of its elements. The result
variable is initialized to 1
and multiplied by each element in the list to compute the final product.