Path: csiph.com!usenet.pasdenom.info!news.albasani.net!newsfeed.freenet.ag!news2.euro.net!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.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'expressions': 0.07; 'parameter': 0.07; 'subject:skip:c 10': 0.07; 'python': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'references.': 0.09; 'stored': 0.10; "'at": 0.16; 'bind': 0.16; 'funcs': 0.16; 'helps.': 0.16; 'lambda': 0.16; 'message-id:@dough.gmane.org': 0.16; 'received:80.91.229.3': 0.16; 'received:plane.gmane.org': 0.16; 'simplest': 0.16; 'variable': 0.20; 'references': 0.23; 'this:': 0.23; 'header:In-Reply-To:1': 0.25; 'header:User- Agent:1': 0.26; 'header:X-Complaints-To:1': 0.28; 'subject:list': 0.28; 'print': 0.32; 'anyone': 0.33; 'to:addr:python-list': 0.33; 'received:org': 0.36; 'does': 0.37; 'subject:: ': 0.38; 'gives': 0.39; 'to:addr:python.org': 0.39; 'header:Received:5': 0.40; 'more': 0.63; 'importantly,': 0.65; 'received:93': 0.72; '(they': 0.84; 'received:hr': 0.84; 'why?': 0.84; 'subject:funny': 0.91 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: =?UTF-8?B?SnVya28gR29zcG9kbmV0acSH?= Subject: Re: lambda in list comprehension acting funny Date: Wed, 11 Jul 2012 09:01:18 +0200 Organization: PKE sistemi d.o.o. References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Gmane-NNTP-Posting-Host: 93-139-12-146.adsl.net.t-com.hr User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20120614 Thunderbird/13.0.1 In-Reply-To: X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.12 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: 30 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1341990101 news.xs4all.nl 6872 [2001:888:2000:d::a6]:40629 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:25168 Hi. >> funcs = [ lambda x: x**i for i in range( 5 ) ] >> print funcs[0]( 2 ) >> >> This gives me >> 16 >> >> When I was excepting >> 1 >> >> Does anyone know why? Just the way Python lambda expressions bind their variable references. Inner 'i' references the outer scope's 'i' variable and not its value 'at the time the lambda got defined'. > And more importantly, what's the simplest way to achieve the latter? :) Try giving the lambda a default parameter (they get calculated and have their value stored at the time the lambda is defined) like this: funcs = [ lambda x, i=i: x**i for i in range( 5 ) ] Hope this helps. Best regards, Jurko Gospodnetić