Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is sum() in Python?

Mahnoor Zaheer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The sum() method in Python returns the sum of the iterable object inside it.

Syntax

This method is declared as follows:

The syntax of sum() method in Python

Parameters

Two parameters can go inside the sum() method:

  • an iterable object
  • an additive value

The iterable object can be a list or a tuple.

The additive value is an optional parameter that gets added to the final sum of the iterable object.

Return value

The return value of the sum() method can be an integer or a floating-point number.

Example

In the example below, x is a tuple of integers and val is the additive value. Since the additive value is an optional parameter, the sum() method can also be used without it.

In the second example, sum() only returns the sum of the integers inside x because it does not have the second optional argument in it.

# Sum() method with both parameters
x = (1, 2, 3, 4, 5)
val = 10
print sum(x, val)
# Sum() method with the only mandatory parameter
print sum(x)

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring