Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.stack.nl!newsfeed.xs4all.nl!newsfeed4a.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.036 X-Spam-Evidence: '*H*': 0.93; '*S*': 0.00; 'modifying': 0.07; 'cc:addr :python-list': 0.11; 'from:addr:rosuav': 0.16; 'from:name:chris angelico': 0.16; 'iterating': 0.16; 'sat,': 0.16; 'wrote:': 0.18; 'cc:addr:python.org': 0.22; 'certainly': 0.24; 'cc:2**0': 0.24; 'header:In-Reply-To:1': 0.27; 'michael': 0.29; 'message- id:@mail.gmail.com': 0.30; '13,': 0.31; 'sep': 0.31; 'something': 0.35; 'received:google.com': 0.35; 'subject:data': 0.36; 'list': 0.37; 'pm,': 0.38; "you're": 0.61; 'welle': 0.84; 'to:none': 0.92 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:in-reply-to:references:date:message-id:subject:from:cc :content-type; bh=MJnuyNZYiyuVyxoPzIo3ju6J5fK9ib1tnW3iU5y7YhI=; b=v9q7LNRhdeTHVWNuB8G1upuNFdsPjZHBp3X8ld5ARRI6ImTruBMbhl4aPBueUzBuaJ jCHgS/6h6brfmLCoZ0GL7a4Z+oPFOoZaxuCCJ/mll/Vay4dkf3WHzfIR3uP/8CXjiGAY 7LatRUmYHWH8nF/jutrB32aut2F8goetYNhQPQCsDDRyHIjE0FQlZbhU+ZeLWDV55v+M JVgdaUqUZysB2dPa7E2sFI3XvRRr90lyWfCo3V1GBpPmcYK7Hd0/lo43ik9Fmww53C6K tDTyB7cAGUjtv7ZxxGoHWjy5R/hd9xSySbewJITL8UUxvueeyOuN1fn1AUvyl9wrtuQ/ 32mQ== MIME-Version: 1.0 X-Received: by 10.50.80.76 with SMTP id p12mr7874918igx.34.1410589334886; Fri, 12 Sep 2014 23:22:14 -0700 (PDT) In-Reply-To: References: Date: Sat, 13 Sep 2014 16:22:14 +1000 Subject: Re: Iterator, modify data in loop body From: Chris Angelico Cc: "python-list@python.org" Content-Type: text/plain; charset=UTF-8 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 16 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1410589338 news.xs4all.nl 2917 [2001:888:2000:d::a6]:57954 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:77832 On Sat, Sep 13, 2014 at 4:09 PM, Michael Welle 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