Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # list_filter_comprehension.py
- # python has buitin funtction for list comprehension
- """ 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"""
- def odd(n):
- return n%2
- li=[1,2,3,4,5,6,7,8,9,10,-1,-2]
- odd_list = filter(odd,li)
- print odd_list
- # one line filter
- odd_nlist=filter(lambda x : x%2 , li)
- print odd_nlist
- # the same task can be achieved in other ways also
- # using list comprehension
- odd_list1=[f for f in li if(odd(f))]
- print odd_list1
- # using for loop
- filtered_list=[]
- for n in li:
- if odd(n):
- filtered_list.append(n)
- print filtered_list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement