Help With filter().

James Logajan JamesL at Lugoj.Com
Thu Jul 12 02:28:44 CEST 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