Rachel Green
Rachel Green

Reputation: 47

Summing list: Skip first even number

I am trying to sum a list but skip the first even number and then continue adding the rest of the list including the rest of the even numbers but I can't seem to get it quite right.

list = [-3, -7, -1, 0, 1, 2, 3, 4, 5, 6, 7] 
def sum_num(num_list):
    sum = 0
    for i in num_list:
        if i % 2 == 0:
            continue
        sum += i
    return sum 
print sum_num(list)

Either I sum none of the even numbers or all of them. How do I make it so it just skips the first even number? Thanks!

Upvotes: 3

Views: 1000

Answers (2)

Jon Clements
Jon Clements

Reputation: 142126

You can also take advantage of itertools.takewhile for this, eg:

from itertools import takewhile

def sum_num(num_list):
    it = iter(num_list)
    before_first_even = takewhile(lambda L: L % 2 != 0, it)
    return sum(before_first_even) + sum(it)

data = [-3, -7, -1, 0, 1, 2, 3, 4, 5, 6, 7]
result = sum_num(data)
# 17

This creates an iterator over num_list and consumes that to calculate the sum until the first even number... then it is left with the remainder of the list (excluding the first even number), so we add the sum of those and return the value... This avoids keeping a variable around to check if we've seen an even value or not yet...

Upvotes: 3

mbomb007
mbomb007

Reputation: 4231

Change your if statement to only succeed once.

def sum_num(num_list):
    total = 0
    once = False
    for i in num_list:
        if i % 2 == 0 and not once:
            once = True
            continue
        total += i
    return total

After it skips the first even, your Boolean once will be True, causing the if conditional to fail for successive evens.

Upvotes: 4

Related Questions