# [python] How to emulate sum() using a list comprehension?

``````>>> from operator import mul
>>> nums = [1, 2, 3]
>>> reduce(mul, nums)
6
``````

On Python 3 you will need to add this import: `from functools import reduce`

Implementation Artifact

In Python `2.5` / `2.6` You could use `vars()['_[1]']` to refer to the list comprehension currently under construction. This is horrible and should never be used but it's the closest thing to what you mentioned in the question (using a list comp to emulate a product).

``````>>> nums = [1, 2, 3]
>>> [n * (vars()['_[1]'] or [1])[-1] for n in nums][-1]
6
``````
Question

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 :

``````list = [1, 2, 3]
product = [magic_here for i in list]

#product is expected to be 6
``````

Code that is doing the same :

``````def product_of(input):
result = 1
for i in input:
result *= i
return result
``````

It is possible to achieve by using lambda with list comprehension Since we can't assign a value in list comprehension we go with lambda

Solution:

``````>>> (lambda number_list, sum=0:[sum for number in number_list for sum in [sum + number]][-1])([1, 2, 3, 4, 5])
>>> 15
``````

Something like this:

``````>>> a = [1,2,3]
>>> reduce(lambda x, y: x*y, a)
6
``````

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)
``````