简体   繁体   中英

How to add each element of a list to each other

In this given list : [1, 2, 3, 4, 5, ..] . I'm trying to add 1 + 2 + 3 + 4 + 5. Please help, I'm new to Python.

 output = sum([1,2,3,4,5])

 print(output)

You can use something like:

listsum =0
for i in list :
    listsum+=i
print ("Sum of list elements is:", sum)

OR

print(sum(list))

Note: here list is the name of the variable that is holding your list.

You can use the sum function

l1=[1,2,2,4,5,6,7]
print(f"Sum of {'+'.join([str(x) for x in l1])} is: {sum(l1)}")

There are two ways: 1 Manual:

sum=0
list1= [1,2,3,4,5]
for v in list1:
    sum+=v
print(sum)
  1. Python way:
list1 = [1,2,3,4,5]
print(sum(list1)) # this will directly print out sum

You can use the 'sum()' function:

num_list = [1, 2, 3, 4, 5, 6, 7, 8]

sum_of_list = sum(num_list)

print(sum_of_list)
sum1 = 0

list1 = [1, 2, 3, 4, 5] 

for x in range(0, len(list1)):
    sum1 = sum1 + list1[x]

print(sum1)
 

numbers = [1, 2, 3, 4, 5, 1, 4, 5]

Sum = sum(numbers)
print(Sum)

Output will be: 25

In case you want to achieve your total Sum of elements + a number you do below. It means total Sum of elements of Numbers + 10

Sum10 = sum(numbers,10)
print(Sum10)

Output will be: 35

如果要一起添加列表项,请使用以下代码:

sum([1,2,3,4,5])

just use

 sum([1,2,3,4,5,...])

And as you are a beginner, doing following for loop will help you understand for loops as well

my_list = [1,2,3,4,5,...]
my_sum = 0
for each_num in my_list:
    my_sum = each_num + my_sum  # This could also be written as my_sum += each_num
print(my_sum)

Solving problems in a multiple ways will help you reinforce your learning

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM