-4

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.

Peter
  • 2,932
  • 1
  • 12
  • 9

9 Answers9

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

 print(output)
Bharat Agrawal
  • 125
  • 3
  • 11
1

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

Ayansplatt
  • 51
  • 4
0

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.

0

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)}")
0

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
Kamesh Kotwani
  • 104
  • 1
  • 7
0

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)
Pranava Mohan
  • 533
  • 2
  • 8
  • 18
0
sum1 = 0

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

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

print(sum1)
 
Zeryab Hassan Kiani
  • 467
  • 1
  • 7
  • 18
0

if you want to add list items together use this code :

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

masih vaziri
  • 51
  • 2
  • 3
0

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

letdatado
  • 93
  • 1
  • 11