[Tutor] iterating over a changing list
Ed Owens
eowens0124 at gmx.com
Wed Oct 10 21:52:15 CEST 2012
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20121010/1584faa1/attachment.html>
More information about the Tutor
mailing list