The Python for loop doesn't work how I think you expect it to. When you call for
here, Python is literally assigning p[i]
to a new copy of the variable event
. It has no next object or previous object to reference.
If you want to know what your current position is, you'll need to use the enumerate()
function.
for index, event in enumerate(p):
print(index, event)
This would allow you to break your loop or create another subloop, and then re-transverse it from the specified point using reversed()
or something similar.
Your code would look something like:
for p in pattern:
for index, event in enumerate(p):
if event == 1:
for event2 in reversed(p[:index]):
# do the things
I'm assuming you don't need to enumerate your reversal. If you do, changing the the innermost for
statement to for in enumerate(reversed(p[:index]):
should do the trick.
I've used a different event variable in case you wanted to reference the one that originally sent you down the reversal. That is not necessary if you don't need that feature.
Option 2:
An additional way (thanks @Scott) can be done using the p.index(event)
value. It's less pythonic and will break your existing loop (maybe that matters maybe not), but it does work.
for p in pattern:
for event in p:
if event == 1:
new_start = p.index(event)
for p in reversed(p[:new_start]):