From your description of the problem, it sounds like you are removing characters as you iterate - if that's correct, then it would be easiest to use a deque (double-ended queue). It's a useful collection type available in the standard Python library and worth knowing about. If you wanted to pop characters out of the list, and switch the direction in which you're moving through the list, you can use a boolean flag to change directions as you pop from either the front or the back. Here's an example of how you can do that:
from collections import deque
import random
# Populate empty deck with integers 1 to 10
d = deque()
n = 10
for i in range(n):
d.append(i+1)
print("Initial deque:")
print(d)
# Note you can also rotate the dequeue:
d.rotate(2)
d.rotate(-2)
# Pop from the list,
# moving from the front of the list (right) to the back of the list (left).
# If a random event happens, we switch directions and pop from the back (left).
print("Popping:")
move_forward = True
while d:
if(move_forward):
nxt = d.pop()
print("Moving forward: %s"%(nxt))
else:
nxt = d.popleft()
print("Moving backward: %s"%(nxt))
# 70% chance that we continue moving forward
if( random.random() < 0.7 ):
move_forward = not move_forward
This initializes a deque with some integers, then iterates through the deque and removes items, reversing direction 70% of the time. Here's the output of the program, which I believe is the behavior you were looking for:
Initial deque:
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Popping:
Moving forward: 10
Moving backward: 1
Moving backward: 2
Moving forward: 9
Moving backward: 3
Moving backward: 4
Moving forward: 8
Moving forward: 7
Moving backward: 5
Moving forward: 6
Edit: If you wanted to save the characters, instead of losing them, when you pop, you can create a new deque
called e
, and right after you call nxt = d.pop()
or nxt = d.popleft()
, you can append it to e
: e.append(nxt)
. (I don't see any elegant way to preserve the original order of the characters though.)