In: Computer Science
Provided is a list of numbers. For each of the numbers in the list, determine whether they are even. If the number is even, add True to a new list called is_even. If the number is odd, then add False.
num_lst = [3, 20, -1, 9, 10]
**Please use Python**
Question:
Provided is a list of numbers. For each of the numbers in the list, determine whether they are even. If the number is even, add True to a new list called is_even. If the number is odd, then add False.
num_lst = [3, 20, -1, 9, 10]
**Please use Python**
Answer:
Summary: We can implement this function in two approaches . First one is the normal list implementation. And the second one is using anonymous function (a function without a name is called anonymous function) or lambda function. Here we also use another function named map (syntax: map(function,sequence)). The "function" inside the map function performs a specified operation on all the elements of the sequence and the modified elements are returned which can be stored in another sequence.
1st approach:
print("how namy element do you want to enter? ") # taking number
of elements of the list from the user
n=int(input())
lst=[] #declaring an empty list
for i in range(n):
print("enter element: ") #taking inputs one by one
from the user
lst.append(int(input()))
print("your list is: ",lst) #displaying the list given by the
user
#lst=[3,20,-1,9,10] #we can also initialize the list to calculate if we donot need to take inputs from user
is_even=[] #declaring an empty list to store here the final
result
for i in lst:
if(i%2==0):
is_even.append("true")
else:
is_even.append("false")
print("final list is " , is_even)
2nd approach (using lambda function):
print("how namy element do you want to enter? ") # taking number
of elements of the list from the user
n=int(input())
lst=[] #declaring an empty list
for i in range(n):
print("enter element: ") #taking inputs one by one
from the user
lst.append(int(input()))
print("your list is: ",lst) #displaying the list given by the
user
#lst=[3,20,-1,9,10] #we can also initialize the list to calculate if we donot need to take inputs from user
is_even=[] #declaring an empty list to store here the final result
is_even=list(map(lambda x: (x%2 ==0),lst))
print("final lis is " , is_even)