Aloha everyone,
Say I have a list and I want to list through the items in that list printing them out as I go, then I would do this.
list = ['a', 'b', 'c']
for item in list:
print item
This should result in this.
a
b
c
Simple enough.
My issue is that when a certain event occurs, for example reaching a 'b', then I want the loop to continue iterating but start again from the point it has just reached. Therefore the output would be this.
a
b
b
c
I had attempted one solution which went along the lines of this but didn't work.
list = ['a', 'b', 'c']
for item in list:
print item
index = list.index(item)
if item == 'b':
item = list[index - 1]
I had hoped that this would set the item to 'a' so the next iteration would continue on back through to 'b', but that wasn't the case.
Thanks in advance for any help.
Why not the following:
for item in lst:
dostuff()
if item=="b":
dostuff()
>>> def my_iter(seq):
... for item in seq:
... yield item
... if item == 'b':
... yield item
...
>>> for item in my_iter('abc'):
... print item
...
a
b
b
c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With