0

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

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

How can I continue, if lst[i-1] == 3?
not sure I understand? you can use the keyword 'continue' to move to the next iteration of the loop. But I guess you know that?
1

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

2 Comments

How can I continue, if lst[i-1] == 3?
I'm not certain what you are asking. Can you provide an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.