[Tutor] iterating over a changing list

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Oct 10 22:44:09 CEST 2012


On 10/10/2012 20:52, Ed Owens wrote:
> I'm trying to iterate over a list of elements, and make changes to the list
> in front of the element I'm currently working with.  I can update the list,
> but the  'for'  doesn't see the new element.  Here's the code:
>
> import string
>
> def add_element(items, point):
>      items = items[:point+1][:] + [['new']] + items[point+1:]
>      return items
>
> def main():
>      pass
>
> itmlst = [['a'],['b']]
> itmcntr = 0
>
> for itm in itmlst:
>      cmd = ''
>      while True:
>          cmd = raw_input('break, add, print:')
>          if cmd == 'break':
>              break
>          elif cmd == 'add':
>              itmlst = add_element(itmlst,itmcntr)
>          elif cmd == 'print':
>              print 'current item:', itm
>          else:
>              print 'invalid'
>      itmcntr += 1
>      print 'finished with', itm, 'in', itmlst
> print len(itmlst), 'total items in list'
>
> If I provide the inputs: [print add print break print break] at the prompt,
> I get this output
>
> current item: ['a']
> current item: ['a']
> finished with ['a'] in [['a'], ['new'], ['b']]
> current item: ['b']
> finished with ['b'] in [['a'], ['new'], ['b']]
> 3 total items in list
>
> The new element got added, but it wasn't used in the iteration over the list
> of items. Other than setting up a counter and calling len() each loop, is
> there some way to have the changing list recognized within the for loop?
>
> Thanks in advance for any help.
>
> Ed
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Usually handled by iterating over a copy of the list.

for itm in itmlst[:]:

-- 
Cheers.

Mark Lawrence.



More information about the Tutor mailing list