Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met.
What I'm trying to do is this:
for index, item in enumerate(list2):
if item == '||' and list2[index-1] == '||':
del list2[index]
*<some action that resarts the whole process>*
That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with:
['berry','||','pancake'] instead.
Thanks!
And by the way this is repeating of Remove adjacent duplicate elements from a list
The inevitable itertools version, because it just came to me:
I'm not sure what you mean by "restarting". Do you want to start iterating over from the beginning, or simply skip the current iteration?
If it's the latter, then
for
loops supportcontinue
just likewhile
loops do:The above will print the numbers from 0 to 9, except for 5.
If you're talking about starting over from the beginning of the
for
loop, there's no way to do that except "manually", for example by wrapping it in awhile
loop:The above will print the numbers from 0 to 5, then start over from 0 again, and so on indefinitely (not really a great example, I know).
As you can see answering your question leads to some rather convoluted code. Usually a better way can be found, which is why such constructs aren't built into the language
If you are not comfortable using itertools, consider using this loop instead. Not only is it easier to follow than your restarting for loop, it is also more efficient because it doesn't waste time rechecking items that have already been passed over.
That will do what you seem to want. Why you would want to do it is a different matter. Maybe you should take a look at your code and make sure you're not missing an obvious and easier way to do it.
A poor way to think of an algorithm.
You're just filtering, i.e., removing duplicates.
And -- in Python -- you're happiest making copies, not trying to do
del
. In general, there's very little call to usedel
.