F. Böller F. Böller - 4 years ago 213
Python Question

List comprehension as substitute for reduce() in Python

The following python tutorial says that:

List comprehension is a complete substitute for the lambda function as well as the functions


However, it does not mention an example how a list comprehension can substitute a
and I can't think of an example how it should be possible.

Can please someone explain how to achieve a reduce-like functionality with list comprehension or confirm that it isn't possible?

Answer Source

Ideally, list comprehension is to create a new list. Quoting official documentation,

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

whereas reduce is used to reduce an iterable to a single value. Quoting functools.reduce,

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.

So, list comprehension cannot be used as a drop-in replacement for reduce.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download