+ 1
how do I sum elements 2 by 2 list? (python)
so for example, i have a list: l = [1, 2, 3, 4, 5, 6, 7, 8] and so i want to sum all the numbers 2 by 2: 1 + 3 + 5 + 7 = 16
6 ответов
+ 2
Create a "for" loop in increments of 2.
Or write a condition that checks odd numbers using the modulo division operator - "%".
+ 1
If I understand correctly, you need to do the following:
1. Create a new list. Use list comprehension to retrieve numbers, from the original list, that you need in your new list.
2. Use sum() built-in function, or **for** loop to get total.
+ 1
filter list by checking even index position of each values
Then use sum function to get total
print (sum([i for i in l if l.index(i) % 2 == 0]))
0
Python program to find sum of elements in list
total = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
# Iterate each element in list
# and add them in variable total
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total)
0
If I am wrong please correct me
0
Ok I understand