Python filter() function usage


/ Published in: Python
Save to your folder(s)

Shows usage of the Python filter() function


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.