OneBite.Dev - Coding blog in a bite size

find the product of all elements in an array in python

Code snippet on how to find the product of all elements in an array in python

def product_array(arr): 
  
  # Initialize the product to one 
  product = 1
  
  # Loop over each element of array 
  for item in arr: 
    
    # Multiply each element to product 
    product *= item 
  
  # Return the product 
  return product 

arr = [1, 2, 3, 4, 5] 

product_arr = product_array(arr) 
print(product_arr)

This code finds the product of all elements in an array. It begins by defining a function, product_array, which takes an array as an argument. The product of the array is initialized to one. Then, the function uses a loop to iterate over each element of the array. At each iteration, the element is multiplied with the product, and the product is updated. Finally, the function returns the resulting product. To test the code, an array is declared, and the product_array function is called on it. This prints the product of all elements in the array.

python