List comprehension vs filter()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Apr 20 12:16:17 CEST 2011


On Wed, 20 Apr 2011 13:10:21 +1000, 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.

[snip discussion and code]

It should, and does, work as expected, both in the global scope:


>>> lst = [{"type": "calc"}, {"type": "fixed"}, {"type": "spam"}, 
...        {42: None, "type": "CALC"}]
>>> t = lst[0]["type"].lower()
>>> 
>>> filter(lambda x: x["type"].lower() == t, lst)
[{'type': 'calc'}, {42: None, 'type': 'CALC'}]
>>> [i for i in lst if i["type"].lower() == t]
[{'type': 'calc'}, {42: None, 'type': 'CALC'}]

and in a function:

>>> def test():
...     lst = [{"type": "calc"}, {"type": "fixed"}, {"type": "spam"},
...            {42: None, "type": "CALC"}]
...     t = lst[0]["type"].lower()
...     print filter(lambda x: x["type"].lower() == t, lst)
...     print [i for i in lst if i["type"].lower() == t]
...
>>> test()
[{'type': 'calc'}, {42: None, 'type': 'CALC'}]
[{'type': 'calc'}, {42: None, 'type': 'CALC'}]


[...]
> 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.

Let me guess... you're using an IDE?

There's your problem. IDEs often play silly buggers with the environment 
in order to be "clever". You've probably found a bug in whatever IDE 
you're using.

And this is why I won't touch the buggers with a 30 ft pole, at least not 
for anything serious.



-- 
Steven



More information about the Python-list mailing list