+ 1
Why is there error
Trying to separate odd from even and put them in a list https://code.sololearn.com/ckiQh3SOa7uv/?ref=app
4 Answers
+ 1
After return, control goes out of function with returning values.. That's what return means ...
So Among two returns, only one executes anytime..
You can do like this :
def is_even_odd(list1):
even_num = []
odd_num = []
for n in list1:
if n % 2 == 0:
even_num.append(n)
else:
odd_num.append(n)
# return a list
return even_num, odd_num
# Pass list to the function
num = is_even_odd([2, 3, 42, 51, 62, 70, 5, 9])
print("Even numbers are:", num[0])
print("odd numbers are:", num[1])
+ 2
Goodness Ogunlana , Jayakrishnađźđł use num[0] and num[1] because the function returns a list of lists.
This is what the function is returning
[
[2,42,62,70],
[3,51,5,9]
]
+ 1
Thanks it works, but why did you use num[0] and num[1]
+ 1
Goodness Ogunlana
Function returning a tuple so used to unpack as num[0] and num[1] for even_num, odd_num lists..
You can also use like :
even_num, odd_num = is_even_odd([2, 3, 42, 51, 62, 70, 5, 9])
print("Even numbers are:", even_num)
print("odd numbers are:", odd_num)
Hope it helps...