Python sum()

The sum() function adds the items of an iterable and returns the sum. The syntax of sum() is: sum(i

The sum() function adds the items of an iterable and returns the sum.

The syntax of sum() is:

sum(iterable, start)

The sum() function adds start and items of the given iterable from left to right.

sum() Parameters

  • iterable - iterable (list, tuple, dict etc) whose item's sum is to be found. Normally, items of the iterable should be numbers.
  • start (optional) - this value is added to the sum of items of the iterable. The default value of start is 0 (if omitted)

Return Value from sum()

The sum() function returns the sum of start and items of the given iterable.

Example: How sum() function works in Python?

numbers = [2.5, 3, 4, -5]

# start parameter is not provided

numbersSum = sum(numbers)

print(numbersSum)

# start = 10

numbersSum = sum(numbers, 10)

print(numbersSum)

When you run the program, the output will be:

4.5

14.5

Python tuple() Function

The tuple() built-in is used to create a tuple in Python.

In Python, a tuple is an immutable sequence type.

One of ways of creating tuple is by using tuple() built-in.

The syntax of tuple() is:

tuple(iterable)

tuple() Parameters

  • iterable‚Äč (optional) - an iterable (list, range etc.) or an iterator object

If an iterable is passed, corresponding tuple is created. If the iterable is omitted, empty tuple is created.

Example: How to creating tuples using tuple()?

t1 = tuple()

print('t1=', t1)

# creating a tuple from a list

t2 = tuple([1, 4, 6])

print('t2=', t2)

# creating a tuple from a string

t1 = tuple('Python')

print('t1=',t1)

# creating a tuple from a dictionary

t1 = tuple({1: 'one', 2: 'two'})

print('t1=',t1)

When you run the program, the output will be:

t1= ()

t2= (1, 4, 6)

t1= ('P', 'y', 't', 'h', 'o', 'n')

t1= (1, 2)

 

Add comment

CommentList

The file '/Custom/Widgets/ScriptInjection/widget.cshtml' does not exist.