w3resource

Python: Product of list

Python Basic: Exercise-115 with Solution

Write a Python program to compute the product of a list of integers (without using a for loop).

Sample Solution-1:

Python Code:

# Import the 'reduce' function from the 'functools' module.
from functools import reduce

# Define a list named 'nums' containing a series of integers.
nums = [10, 20, 30]

# Print a message along with the original list of numbers.
print("Original list numbers:")
print(nums)

# Calculate the product of the numbers in the list 'nums' using the 'reduce' function
# and a lambda function that multiplies two numbers.
nums_product = reduce((lambda x, y: x * y), nums)

# Print the product of the numbers, obtained without using a for loop.
print("\nProduct of the said numbers (without using a for loop):", nums_product)

Sample Output:

Original list numbers:
[10, 20, 30]
Product of the numbers :  6000

Flowchart:

Flowchart: Compute the product of a list of integers.

Sample Solution-2:

Python Code:

# Import the 'math' module to access the 'prod' function.
import math

# Define a list named 'nums' containing a series of integers.
nums = [10, 20, 30]

# Print a message indicating the original list of numbers.
print("Original list numbers:")
print(nums)

# Calculate the product of the numbers in the list 'nums' using the 'prod' function
# from the 'math' module.
nums_product = math.prod(nums)

# Print the product of the numbers, obtained without using a for loop.
print("\nProduct of the said numbers (without using a for loop):", nums_product)

Sample Output:

Original list numbers:
[10, 20, 30]
Product of the numbers :  6000

Flowchart:

Flowchart: Compute the product of a list of integers.

Python Code Editor:

 

Previous: Write a Python program to filter the positive numbers from a list.
Next: Write a Python program to print Unicode characters.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.