[2559 views]
Do you know to emulate sum() using a list comprehension? There are many programmers who still don’t know about this. Don’t feel bad about that because we are going to cover almost everything about emulating sum () using a list comprehension in python.
Before you should learn to know about emulating sum(), it is necessary to learn something about list comprehension.
In python, comprehension allows us to create new sequences easily with the existing sequence. There are four types of comprehension in python- list comprehension, dictionary comprehension, set comprehension and generator comprehension. List comprehension offer a simple way for creating new lists. It always provides results without even using results or nor. You can iterate and manipulate variable simultaneously.
Suppose you have to compute the product of all elements in the list. There are two ways to do so. For instance:
Another code that do the same:
The fact is it is not possible to emulate because a list comprehension generates a list that with the same length as the input. You have to use other functional tools for aggregating the sequence into a single value.
In the case of functional programming, aggregate is also known as a fold, reduce, accumulate, compress or inject. It is a group of the higher-order functions used for analyzing a recursive data structure. However, it is of no use to combine them and provide a single value. Let’s see various solutions for solving your problem.
You can try to emulate sum() with the help of reduce functionality. Use the following code:
In the latest version of Python 3.8, programmers can use walrus operator to increment a variable and reducing the list to the total sum of its elements.
In the above code, it initializes the total variable to 0. For every item in the list, the variable total is incremented by making the use of current looped item and walrus operator.
The problem can also be solved as given in the given code. This is the beauty of programming. You can solve the same problem using a number of different methods.
Hopefully, you have understood and learned all the ways to emulate sum () using list comprehension.