NineWasps
NineWasps

Reputation: 2273

Error in loop with python

I have list lst = [1, 2, 3, 4, 5, 6, 3, 5, 3] and to every iteration, where elem == 3 I want to print strings before that, while elem not is 3 again. I want to get

2 3:
0 1
1 2
6 3:
3 4
4 5
5 6
8 3:
7 5

But I don't know, how to go to previous string

for i, el in enumerate(lst):
    if lst[i] == 3:
        print i, el
        i -= 1

But it's inly elem-1

Upvotes: 0

Views: 39

Answers (2)

M Hart
M Hart

Reputation: 146

You might try implementing with slices as in:

lst = [1, 2, 3, 4, 5, 6, 3, 5, 3]

start_pos = 0
for idx, val in enumerate(lst):
    if val == 3:
        print idx,val,":"
        for p_idx, p_val in enumerate(lst[start_pos:idx]):
            print p_idx+start_pos,p_val
        start_pos = idx+1

Upvotes: 1

joeButler
joeButler

Reputation: 1711

Something like this?

    lst = [1, 2, 3, 4, 5, 6, 3, 5, 3]
    previous = []

    for i, el in enumerate(lst):
        if lst[i] == 3:
            print i, el,":"
            for p in previous:
                print p[0] , p[1]
            previous = []
        else:
            previous.append((i,el))

Upvotes: 1

Related Questions