Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3633

List comprehension vs filter()

Date 2011-04-20 13:10 +1000
Subject List comprehension vs filter()
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.603.1303269025.9059.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar


Thread

List comprehension vs filter() Chris Angelico <rosuav@gmail.com> - 2011-04-20 13:10 +1000
  Re: List comprehension vs filter() Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-20 10:16 +0000
    Re: List comprehension vs filter() Chris Angelico <rosuav@gmail.com> - 2011-04-20 21:25 +1000
  Re: List comprehension vs filter() Peter Otten <__peter__@web.de> - 2011-04-20 12:41 +0200
    Re: List comprehension vs filter() Ian Kelly <ian.g.kelly@gmail.com> - 2011-04-20 08:44 -0600
    Re: List comprehension vs filter() Chris Angelico <rosuav@gmail.com> - 2011-04-21 04:03 +1000
    Re: List comprehension vs filter() Ian Kelly <ian.g.kelly@gmail.com> - 2011-04-20 12:35 -0600

csiph-web