Is it possible to emulate something like sum() using list comprehension ?
For example - I need to calculate the product of all elements in a list :
l
I complement the answer of Ignacio Vazquez-Abrams with some code that uses the reduce
operator of Python.
list_of_numbers = [1, 5, 10, 100]
reduce(lambda x, y: x + y, list_of_numbers)
which can also be written as
list_of_numbers = [1, 5, 10, 100]
def sum(x, y):
return x + y
reduce(sum, list_of_numbers)
Bonus: Python provides this functionality in the built-in sum
function. This is the most readable expression imo.
list_of_numbers = [1, 5, 10, 100]
sum(list_of_numbers)