Python sum() function
The sum()
function in Python returns the sum of all elements in an iterable (e.g., list, tuple) or the sum of two or more numbers, optionally starting with an initial value.
Syntax
iterable
: The iterable (like a list, tuple, or set) containing the items to be summed.start
(optional): The value to start with. This is added to the sum of the items in the iterable. It defaults to0
.
Return Value
- Returns the total sum of the elements in the iterable, starting from the
start
value if provided.
Examples
Summing a list of numbers:
Using
sum()
with astart
value: Thestart
value is added to the sum of the iterable.Summing a tuple of numbers:
Summing using a
start
value of 0 (default): If nostart
value is provided, it defaults to0
.Summing with a set: You can use a set with the
sum()
function as well.Summing with a generator expression: You can pass a generator expression to
sum()
.
Points to Remember
- The
sum()
function works with numbers, and it cannot directly sum strings or non-numeric types. - It is more efficient for numeric types and sequences but is not suitable for concatenating strings. For string concatenation, use the
join()
function instead.
Summary
- The
sum()
function is used to calculate the sum of numbers in an iterable. - An optional
start
value can be provided, which is added to the total sum. - Works with iterables like lists, tuples, sets, and generator expressions.