Posted By

andrewjsledge on 12/22/11


Tagged

data filter structures lists


Versions (?)

Python filter() function usage


 / Published in: Python
 

Shows usage of the Python filter() function

  1. # Suppose you have a list of people's first names. You want to reduce the list down to only those people whose first names start with "C".
  2.  
  3. people = ['Amy', 'Alice', 'Bobby', 'Charlie', 'Connie', 'David']
  4.  
  5. # You would create a callback function that would look something like this:
  6.  
  7. def starts_with_c(name):
  8. if name[0] == "C":
  9. return True
  10. return False
  11.  
  12. # So then, you would run the filter function
  13.  
  14. starts_with_c_list = filter(starts_with_c, people)
  15. print starts_with_c_list
  16.  
  17. # prints ['Charlie', 'Connie']

Report this snippet  

You need to login to post a comment.