Help With filter().

James Logajan JamesL at Lugoj.Com
Wed Jul 11 20:28:44 EDT 2001


EricIDLE wrote:
> 
> What does filter do? I don't understand when I read it other places.

  newlist = filter(somefunc, somelist)
#### is roughly the same as doing:
  newlist = []
  for entry in somelist:
      if somefunc(entry):
          newlist.append(entry)
####

So the newlist will have only those entries for which somefunc returns a
true value. Note that if you do:
  newlist = filter(None, somelist)
#### this is roughly the same as:
  newlist = []
  for entry in somelist:
      if entry:   # Notice change here.
          newlist.append(entry)
####

Note that if somelist is a string or tuple, then newlist will be a string or
tuple.



More information about the Python-list mailing list