Adding all elements in list

This blog contain program for adding all elements in a list

We will be using for loop in order to add all elements in a list. Same program can be written in multiple ways.

We will start by creating a list of numbers. Below is the list that we have created which contain 5 values

num = [2,5,6,7,8]

Now, define a variable with 0 value

i = 0

Using for loop to add all elements in a list and the result will be stored in the i variable.

for n in num:
    i = n + i

Display the result stored in i variable

print(i)

Output

28

Complete Code

num = [2,5,6,7,8]
i = 0
for n in num:
    i = n + i

print(i)

We can also use sum method to add all elements in a list

num = [2,3,45,6]
print(sum(num))

Output

56
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s