Advertisement
gauravssnl

list_filter_and_comprehension

Sep 30th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. # list_filter_comprehension.py
  2. # python has buitin funtction for list comprehension
  3. """ a function is passed as first argument to  "fiter",and a list as second argument.That function has to take an argument."filter" will return a list containing all the elements for which that function returned true"""
  4.  
  5.  
  6. def odd(n):
  7.     return n%2
  8.  
  9. li=[1,2,3,4,5,6,7,8,9,10,-1,-2]
  10. odd_list = filter(odd,li)
  11. print odd_list
  12.  
  13. # one line filter
  14. odd_nlist=filter(lambda x : x%2 , li)
  15. print odd_nlist
  16. # the same task can be achieved in other ways also
  17. # using list comprehension
  18. odd_list1=[f for f in li if(odd(f))]
  19. print odd_list1
  20. # using for loop
  21. filtered_list=[]
  22. for n in li:
  23.     if odd(n):
  24.         filtered_list.append(n)
  25.  
  26. print filtered_list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement