In: Computer Science
Please attach the output screenshots, narrative descriptions, or paste the Python codes when requested.
Task 2
Please define a function that extracts the even numbers in a given list. For example, given a list x = [2,3,5,6,7], the function will return a sublist [2,6] because 2 and 6 are even numbers in the list x.
The input of this function should be a list, and the output of the function should be a list as well (the sublist).
You can try the inline for loop with conditions to make the solution super simple.
Task 3
Use inline for loop to extract the common elements in two lists. For example, if x = [1,2,3], and y = [2,3,4], the result should be [2,3].
Hint: to check if a value exists in a list, you can use the “in” command. For example: we define two variables
a = 2 in [1,2,3]
b = 4 in [1,2,3].
After executing the codes, a will be a “True”, and b will be a “False”.
Answer 1:
def evenList(myList):
res=[]
#iterating throught list
for x in myList:
#checking if even than adding to new list
if x%2==0:
res.append(x)
#returning new list
return res
print(evenList([2,3,5,6,7]))
Answer 2:
def commonList(list1,list2):
res=[]
#iterating throught list
for x in list1:
#checking if element exist in list2 than adding to new list
if x in list2:
res.append(x)
#returning new list
return res
print(commonList([2,3,5,6,7],[2,3,4,7,9]))
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me