×

Search anything:

Python Sum Lambda [3 different ways]

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have presented 3 approaches to use lambda to get the sum of all elements of a list along with complete Python code.

Table of contents:

  1. Lambda to sum 2 elements
  2. Lambda to get sum of a list using reduce
  3. Pure Lambda to get sum of a list

Lambda to sum 2 elements

Adding 2 elements using lambda in Python is straight forward. The lambda takes in two input parameters and returns the sum of the two elements. Following Python code demonstrates the process:

f = lambda x, y: x+y
sum = f(2, 9)
print(sum)

Output:

11

The challenge is to get the sum of all elements of a list using lambda.

Lambda to get sum of a list using reduce

We can leverage the above lambda to get the sum of two elements to find the sum of all elements of a list. The solution is to use reduce() built-in functions in Python.

reduce() built-in function applies the same function on all elements of an iterable object like list. This can be used to apply the previous lambda on each element of the list.

Following Python code using lambda explains the concept:

from functools import reduce 

list = [59, 47, 7, 17, 45]
f = lambda x, y: x+y
sum = reduce(f, list)
print(sum)

Output:

175

Reduce applies the lambda on the first two elements followed by the result as the first element and the third element as the second element in lambda and so on. This explains the concept/ order in which the lambda is applied using reduce():

((((59, 47), 7), 17), 45)

This lambda in Python helps us find the sum of all elements of an iterable.

Pure Lambda to get sum of a list

It is possible to avoid the use of reduce(). The key is that:

  • If size of list is 1, then the sum is same as the first element.
  • Else, add the first element of the list to the sum of the rest of the list which is calculated using the lambda.

Following Python code using lambda explains the concept:

list = [59, 47, 7, 17, 45]
f = lambda l: l[0] if len(l) == 1 else l[0] + f(l[1:])
sum = f(list)
print(sum)

Output:

175

This is a pure approach of using only lambda to find the sum of all elements in an iterable.

Concluding Note

With this article at OpenGenus, you must have the complete idea of how to get the sum of all elements of a list using Lambda.

Ned Nedialkov

Ned Nedialkov

Professor of Computing at McMaster University | Ph.D in Computer Science from University of Toronto in 1999 | Native of Bulgaria | Research in Scientific Computing

Read More

Improved & Reviewed by:


OpenGenus Foundation OpenGenus Foundation
Python Sum Lambda [3 different ways]
Share this