Sum of specific index in 2-d list

Viewed 61

How can I use a for loop to print out and calculate the sum of the second character in each line (2,6,8,2,6,8)?

a = [[1, 2, 3, 4], [5, 6], [7, 8, 9], [1, 2, 2, 4], [5, 6,2], [7, 8, 9]]
s = 0
for i in range(len(a)):
    for j in range(len(a[i])):
        s += a[i][j]
print(s)
1 Answers

You could loop over the list's length and access each sublist by index:

s = 0
for i in range(len(a)):
    s += a[i][1]

And of course, you could replace this with a generator expression:

s = sum(x[1] for x in a)
Related