Product of all elements

Python Practice › List Programs › Program 4

Product of all elements

EasyList Programs · 4 of 100

Write a Python program to find the product of all elements in a list.

Input
[2, 3, 4, 5]
Output
120 120

Approach

  1. Start at 1 and multiply, or use math.prod().

Solution

Python
import math numbers = [2, 3, 4, 5]product = 1for n in numbers:    product *= nprint(product, math.prod(numbers))
Output
120 120

Line by line

Line 4

Starting at 1 (not 0) keeps the product correct.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Sum of all elements

Python Practice › List Programs › Program 3

Sum of all elements

EasyList Programs · 3 of 100

Write a Python program to calculate the sum of all elements in a list.

Input
[12, 7, 33, 5, 21]
Output
78 78

Approach

  1. Add each item to a total, or use sum().

Solution

Python
numbers = [12, 7, 33, 5, 21]total = 0for n in numbers:    total += nprint(total, sum(numbers))
Output
78 78

Line by line

Lines 3-4

The loop adds each number to the running total.

Line 5

The built-in sum() gives the same answer.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Python NumPy Programs with Solutions

Python Practice › NumPy Programs

Python NumPy Programs with Solutions

100 programs100 easy0 medium0 hard

100 NumPy programs: creating arrays and matrices, element-wise tests and comparisons, indexing, reshaping, sorting, set operations, NaN handling, statistics and rounding. The outputs come from NumPy 2.5; the in-browser Try it uses an older NumPy, so a few printouts may look slightly different.

Before you start

Read the NumPy lesson first if the topic is new to you.

All programs