Custom Search

Tuesday, April 26, 2011

python how to find even/odd numbers from a list using list comprehension and Filter

python how to find even/odd numbers from a list using list comprehension and Filter
my_list = [1,2,3,4,5,6,7,8,9,10]

#find even/odd numbers from a list using list comprehension
even_list = [x for x in my_list if not x%2]
odd_list = [x for x in my_list if x%2]
print "\n-------even_list--------", even_list
print "\n-------odd_list--------", odd_list

=========================

#find even/odd numbers from a list using Filter
even_list = filter(lambda x:not x%2, my_list)
odd_list = filter(lambda x:x%2, my_list)
print "\n-------even_list--------", even_list
print "\n-------odd_list--------", odd_list

=========================

def even_check(x):
if not x%2:
return True
return False

def odd_check(x):
if not x%2:
return False
return True

#find even/odd numbers from a list using Filter
even_list = filter(even_check, my_list)
odd_list = filter(odd_check, my_list)
print "\n-------even_list--------", even_list
print "\n-------odd_list--------", odd_list


OUTPUT
======
-------even_list-------- [2, 4, 6, 8, 10]

-------odd_list-------- [1, 3, 5, 7, 9]

-------even_list-------- [2, 4, 6, 8, 10]

-------odd_list-------- [1, 3, 5, 7, 9]

-------even_list-------- [2, 4, 6, 8, 10]

-------odd_list-------- [1, 3, 5, 7, 9]

No comments:

Post a Comment