Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the list item in a Python for loop

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.

like image 480
alexedwardjones Avatar asked Dec 04 '25 06:12

alexedwardjones


2 Answers

Why not the following:

for item in lst:
    dostuff()
    if item=="b":
        dostuff()
like image 133
phimuemue Avatar answered Dec 07 '25 00:12

phimuemue


>>> 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
like image 32
newtover Avatar answered Dec 07 '25 00:12

newtover