How to emulate sum() using a list comprehension?
No; a list comprehension produces a list that is just as long as its input. You will need one of Python's other functional tools (specifically reduce()
in this case) to fold the sequence into a single value.
>>> from functools import reduce
>>> from operator import mul
>>> nums = [1, 2, 3]
>>> reduce(mul, nums)
6
Python 3 Hack
In regards to approaches such as [total := total + x for x in [1, 2, 3, 4, 5]]
This is a terrible idea. The general idea of emulate sum()
using a list comprehension goes against the whole purpose of a list comprehension. You should not use a list comprehension in this case.
Python 2.5 / 2.6 Hack
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
Starting in Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can use and increment a variable within a list comprehension and thus reduce a list to the sum of its elements:
total = 0
[total := total + x for x in [1, 2, 3, 4, 5]]
# total = 15
This:
- Initialises a variable
total
to0
- For each item,
total
is incremented by the current looped item (total := total + x
) via an assignment expression