Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: List comprehension vs filter() Followup-To: comp.lang.python Date: Wed, 20 Apr 2011 12:41:18 +0200 Organization: None Lines: 48 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: solani.org 1303296070 15515 eJwNysERACEIA8CWUJKg5Rwc9l+CfneWrqEKiAIPz5qVI21mmJrfo6QtlnslXu1tPzyI3iXYvBOMEGY= (20 Apr 2011 10:41:10 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Wed, 20 Apr 2011 10:41:10 +0000 (UTC) X-User-ID: eJwNxckBwCAIBMCWUFiOclyU/ktI5jNQX95hDjcMxppT0v+bnrGPKfQGoUFeiaYUreJs87wdMgW+59j5Jld+XroVpQ== Cancel-Lock: sha1:uZ4H1A5POevZnCW66CJZuNhpwQY= X-NNTP-Posting-Host: eJwNy8ERACEIBMGUUFnUcG6BzT+E8zOPrhqsGJHbA+EQVPI0XeZuvshpJnjq25ExujSBE0ODswo0EUDfWYssRxfvjtMPqXf8JjIbgQ== Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:3683 Chris Angelico wrote: > Context: Embedded Python interpreter, version 2.6.6 > > I have a list of dictionaries, where each dictionary has a "type" > element which is a string. I want to reduce the list to just the > dictionaries which have the same "type" as the first one. > > lst=[{"type":"calc",...},{"type":"fixed",...},{"type":"calc",...},...] > > I'm seeing a weird difference between two otherwise-equivalent-looking > ways of doing the job. > > type=lst[0]["type"].lower() > > lst=filter(lambda x: x["type"].lower()==type,lst) # Restrict to that one > type > > lst=[i for i in lst if i["type"].lower()==type] # Restrict to that one > type > > If I use the filter() method, the resulting list is completely empty. > If I use the list comprehension, it works perfectly. Oddly, either > version works in the stand-alone interpreter. > > I have no idea where to start looking for the problem. Hints, please! > > Chris Angelico The assignment writes to the local namespace, the lambda function reads from the global namespace; this will only work as expected if the two namespaces are the same: >>> exec """type = 42; print filter(lambda x: x == type, [42])""" in {}, {} [] >>> ns = {} >>> exec """type = 42; print filter(lambda x: x == type, [42])""" in ns [42] The list comprehension doesn't introduce another namespace, at least in 2.x: $ python2.7 -c 'exec("type = 42; print([x for x in [42] if x == type])", {}, {})' [42] $ python3.2 -c 'exec("type = 42; print([x for x in [42] if x == type])", {}, {})' []