+ 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

14th Mar 2023, 2:44 PM
sunshine
sunshine - avatar
6 Réponses
+ 2
Create a "for" loop in increments of 2. Or write a condition that checks odd numbers using the modulo division operator - "%".
14th Mar 2023, 3:17 PM
Solo
Solo - avatar
+ 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.
14th Mar 2023, 2:58 PM
Lamron
Lamron - avatar
+ 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]))
14th Mar 2023, 3:49 PM
A͢J
A͢J - avatar
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)
14th Mar 2023, 3:13 PM
Herobrine
Herobrine - avatar
0
If I am wrong please correct me
14th Mar 2023, 3:14 PM
Herobrine
Herobrine - avatar
0
Ok I understand
14th Mar 2023, 4:07 PM
Herobrine
Herobrine - avatar