w3resource

Python: Multiply all the numbers in a given list using lambda


43. Multiply Numbers in List Lambda

Write a Python program to multiply all the numbers in a given list using lambda.

Sample Solution:

Python Code :

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

# Define a function 'multiple_list' that multiplies all numbers in a list using 'reduce'
def mutiple_list(nums):
    # Use the 'reduce' function with a lambda to multiply all elements in the 'nums' list
    result = reduce(lambda x, y: x * y, nums)
    
    # Return the result of multiplying all numbers in the list
    return result

# Create a list 'nums' containing integers and one negative number
nums = [4, 3, 2, 2, -1, 18]

# Print the original list 'nums' and multiply all its numbers using 'multiple_list' function
print("Original list:")
print(nums)
print("Multiply all the numbers of the said list:", mutiple_list(nums))

# Create another list 'nums' containing integers
nums = [2, 4, 8, 8, 3, 2, 9]

# Print the original list 'nums' and multiply all its numbers using 'multiple_list' function
print("\nOriginal list:")
print(nums)
print("Multiply all the numbers of the said list:", mutiple_list(nums)) 

Sample Output:

Original list: 
[4, 3, 2, 2, -1, 18]
Mmultiply all the numbers of the said list: -864

Original list: 
[2, 4, 8, 8, 3, 2, 9]
Mmultiply all the numbers of the said list: 27648

For more Practice: Solve these Related Problems:

  • Write a Python program to multiply all positive numbers in a given list using lambda.
  • Write a Python program to multiply numbers at even indices in a list using lambda.
  • Write a Python program to multiply all numbers in a list and then add a specified constant to the result using lambda.
  • Write a Python program to multiply all numbers in a list and then compute the modulus of the result with a given divisor using lambda.

Go to:


Previous: Write a Python program to calculate the product of a given list of numbers using lambda.
Next: Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.