Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Product of squares in list
The product of squares in a list means calculating the square of each element first, then multiplying all the squared values together. Python provides multiple approaches to solve this problem efficiently.
Understanding the Problem
Given a list like [9, -4, 8, -1], we need to ?
- Square each element: 9² = 81, (-4)² = 16, 8² = 64, (-1)² = 1
- Multiply all squares: 81 × 16 × 64 × 1 = 82944
Method 1: Using Iteration
Iterate through each element, square it, and multiply with the running product ?
# Initialize the list with integer elements
numbers = [9, -4, 8, -1]
# Initialize product to 1 (multiplying by 1 preserves the value)
product = 1
# Iterate through the list
for num in numbers:
# Calculate square and multiply with product
product *= num ** 2
print("Product of squares:", product)
Product of squares: 82944
Method 2: Using functools.reduce()
Use reduce() with a lambda function to multiply all squared values ?
from functools import reduce
# Initialize the list
numbers = [9, -4, 8, -1]
# Use reduce with lambda to multiply all squared values
product = reduce(lambda a, b: a * b, [x**2 for x in numbers])
print("Product of squares:", product)
Product of squares: 82944
Method 3: Using math.prod() (Python 3.8+)
The most concise approach using the built-in math.prod() function ?
import math
numbers = [9, -4, 8, -1]
# Calculate product of squares using math.prod()
product = math.prod(x**2 for x in numbers)
print("Product of squares:", product)
Product of squares: 82944
Comparison
| Method | Time Complexity | Readability | Python Version |
|---|---|---|---|
| Iteration | O(n) | High | All versions |
| functools.reduce() | O(n) | Medium | All versions |
| math.prod() | O(n) | Highest | 3.8+ |
Conclusion
Use math.prod() for the cleanest solution in Python 3.8+. For older versions, iteration provides the most readable approach. All methods have O(n) time complexity.
Advertisements
