Python - Sum of Cubes in List
We are having a list we need to find sum of cubes of list. For example, n = [1, 2, 3, 4] we are given this list we need to find sum of cubes of each element of list so that resultant output should be 100.
Using List Comprehension with sum()
List comprehension with sum() allows us to compute sum of cubes of elements in a list in a concise one-liner. It iterates through the list cubes each element and aggregates the results using sum().
n = [1, 2, 3, 4]
# Compute the sum of cubes using list comprehension with sum()
res = sum(x**3 for x in n)
print(res)
Output
100
Explanation:
- Generator expression x**3 for x in n computes the cube of each element in n.
- sum() function then adds up all the cubed values, resulting in the total sum of cubes.
Using map()
with sum()
Using map()
with sum(),
we apply the cube operation to each element in the list without using an explicit loop map()
function processes each element and sum()
aggregates the cubed values into a final result.
n = [1, 2, 3, 4]
# Compute the sum of cubes using map() with sum()
res = sum(map(lambda x: x**3, n))
print(res)
Output
100
Explanation:
- map(lambda x: x**3, n) applies the cube operation to each element in n generating a transformed sequence.
- sum() function then aggregates these cubed values producing the total sum of cubes.
Using a for
Loop
Using a for loop, we iterate through the list compute the cube of each element, and accumulate the results in a variable. This method provides a step-by-step approach to summing the cubes of elements.
n = [1, 2, 3, 4]
res = 0
for num in n:
# Compute the cube and add it to the result
res += num**3
print(res)
Output
100
Explanation:
- For loop iterates through list computing the cube of each element and adding it to res.
- This approach accumulates the sum incrementally making it an explicit and easy-to-understand method for summing cubes.