0

Lists input

#Write a function which accepts an input list of numbers and returns a list which includes only the even numbers in the input list. If there are no even numbers in the input numbers then your function should return an empty list. My Output is [ ].I want function to check element in the list for even number e = [] sample_list = [5,7,6,8,6,4,2] def even_num(sample_list): for n in sample_list: if n % 2 == 0: return n else: return e print(even_num(sample_list))

3rd Feb 2022, 3:28 AM
Knowledge Is Power
Knowledge Is Power - avatar
2 ответов
+ 3
A return statement will exit from the function. Right now you only return the first number if it happens to be even. You need to collect all even elements. You can do that in a loop as you have now by pushing even numbers into a new list. def even_num(sample_list): e = [] for n in sample_list: if n % 2 == 0: e.append(n) return e Or, in a more pythonic fashion, use list comprehension. def even_num(sample_list): return [e for e in sample_list if e%2==0]
3rd Feb 2022, 4:02 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Thank you so much!!👍
5th Feb 2022, 1:01 AM
Knowledge Is Power
Knowledge Is Power - avatar