Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Antoon Pardon Newsgroups: comp.lang.python Subject: Re: Why lambda in loop requires default? Date: Mon, 28 Mar 2016 22:26:48 +0200 Lines: 38 Message-ID: References: <56F73B60.9020603@gmail.com> Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252 Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de Kw20YrIWsuCHtG1G5vUOnAqiOXnHZ22Mb3xeqf1R35JA== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.006 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'python,': 0.02; 'loop.': 0.09; 'ruby,': 0.09; 'subject:Why': 0.09; 'python': 0.10; 'def': 0.13; 'intermediate': 0.15; '(lambda': 0.16; 'received:adsl- dyn.isp.belgacom.be': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'scopes': 0.16; 'subject:default': 0.16; 'variable.': 0.16; 'creates': 0.18; 'variable': 0.18; 'language': 0.19; 'anonymous': 0.22; 'this:': 0.23; 'thus': 0.24; 'header:In- Reply-To:1': 0.24; 'header:User-Agent:1': 0.26; "doesn't": 0.26; 'received:be': 0.30; 'guess': 0.31; 'run': 0.33; 'running': 0.34; 'but': 0.36; 'instead': 0.36; 'to:addr:python-list': 0.36; 'subject:?': 0.36; 'subject:: ': 0.37; 'being': 0.37; 'end': 0.39; 'why': 0.39; 'received:192': 0.39; 'to:addr:python.org': 0.40; 'your': 0.60; 'provide': 0.61; 'charset:windows-1252': 0.62; 'pardon': 0.84; 'received:195.238': 0.84; 'schreef': 0.84; 'received:192.168.1.7': 0.91 X-Belgacom-Dynamic: yes X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: A2CbAABlkvlW/2LF9VENUL9yAQ2BcIYNAoFcFAEBAQEBAQGFTQEBAwEnUQYLCyEWDwkDAgECAUUTCAKIG68OjGiEFAEBCAIehh6ERIUIhQoBBJdhgVKMNI8LjwoeAQGEKYlkAQEB User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Icedove/38.5.0 In-Reply-To: <56F73B60.9020603@gmail.com> X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:105920 Op 27-03-16 om 03:46 schreef gvim: > Given that Python, like Ruby, is an object-oriented language why doesn't this: It has nothing to do with being object-oriented but by how scopes are used > def m(): > a = [] > for i in range(3): a.append(lambda: i) > return a Python doesn't create a new scope for the suite of the for loop. If you want an intermediate scope, you have to provide it your self. Like the following. def m(): a = [] for i in range(3): a.append((lambda i: (lambda : i))(i)) return a > b = m() > for n in range(3): print(b[n]()) # => 2 2 2 > > ... work the same as this in Ruby: > > def m > a = [] > (0..2).each {|i| a << ->(){i}} > a > end I don't know ruby but I guess the block creates a new scope and thus running the block is like calling an anonymous function. So the i in each run of the block is a new instantiation of the variable instead of being the same variable. -- Antoon Pardon