iterate over list while changing it

Daniel Stutzbach daniel at stutzbachenterprises.com
Thu Oct 1 05:19:02 CEST 2009


On Thu, Sep 24, 2009 at 3:32 PM, Torsten Mohr <tmohr at s.netic.de> wrote:

> a = [1, 2, 3, 4, 5, 6]
>
> for i, x in enumerate(a):
>    if x == 3:
>        a.pop(i)
>        continue
>
>    if x == 4:
>        a.push(88)
>
>    print "i", i, "x", x
>
> I'd like to iterate over a list and change that list while iterating.
> I'd still like to work on all items in that list, which is not happening
> in the example above.
>

I assume that by "a.push" you meant "a.append".

I believe this will do what you want:

a = [1, 2, 3, 4, 5, 6]
i = 0
while i < len(a):
   x = a[i]
   if x == 3:
       a.pop(i)
       i += 1
       continue

   if x == 4:
       a.append(88)

   print "i", i, "x", x
   i += 1

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC <http://stutzbachenterprises.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090930/0688d0a8/attachment.html>


More information about the Python-list mailing list