Search code examples
pythonlistenumerate

Accessing a tuple in enumerate?


I want to iterate through a list and sum all the elements. Except, if the number is a 5, I want to skip the number following that 5. So for example:

x=[1,2,3,4,5,6,7,5,4,3] #should results in 30.

I'm just not sure how I can access the index of a tuple, when I use enumerate. What I want to do, is use an if statement, that if the number at the previous index == 5, continue the loop.

Thanks you


Solution

  • Not a fan of bug-ridden one-liners that get upvoted.

    So here's the answer with a for-loop.

    x=[1,2,3,4,5,6,7,5,4,3, 5] #should results in 35. 
    
    s = 0
    for i, v in enumerate(x):
        if i != 0 and x[i-1] == 5: 
            continue 
        s += v
    
    print(s)