Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #77832

Re: Iterator, modify data in loop body

References <uk3debxpcg.ln2@news.c0t0d0s0.de>
Date 2014-09-13 16:22 +1000
Subject Re: Iterator, modify data in loop body
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.13990.1410589338.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Sep 13, 2014 at 4:09 PM, Michael Welle <mwe012008@gmx.net> wrote:
> foo = [1,2,3,4]
> it = iter(foo)
>
> for e in it:
>     if e % 2 == 0:
>         x.append(e)

A better way to do this is with a list comprehension:

x = [e for e in foo if e %2 == 0]

Modifying something that you're iterating over is unspecified, I
believe. Certainly it's not a good idea.

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Iterator, modify data in loop body Michael Welle <mwe012008@gmx.net> - 2014-09-13 08:09 +0200
  Re: Iterator, modify data in loop body Chris Angelico <rosuav@gmail.com> - 2014-09-13 16:22 +1000
    Re: Iterator, modify data in loop body Michael Welle <mwe012008@gmx.net> - 2014-09-13 09:01 +0200
      Re: Iterator, modify data in loop body Chris Angelico <rosuav@gmail.com> - 2014-09-13 17:22 +1000
        Re: Iterator, modify data in loop body Michael Welle <mwe012008@gmx.net> - 2014-09-13 09:39 +0200
          Re: Iterator, modify data in loop body Ian Kelly <ian.g.kelly@gmail.com> - 2014-09-13 09:27 -0600
            Re: Iterator, modify data in loop body Michael Welle <mwe012008@gmx.net> - 2014-09-13 18:58 +0200
          Re: Iterator, modify data in loop body Chris Angelico <rosuav@gmail.com> - 2014-09-14 01:32 +1000
        Re: Iterator, modify data in loop body Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2014-09-16 10:49 +0200
          Re: Iterator, modify data in loop body Chris Angelico <rosuav@gmail.com> - 2014-09-17 01:19 +1000
  Re: Iterator, modify data in loop body Peter Otten <__peter__@web.de> - 2014-09-13 09:34 +0200
    Re: Iterator, modify data in loop body Michael Welle <mwe012008@gmx.net> - 2014-09-13 09:55 +0200

csiph-web