There’s a number of ways to do this. You could create a function that specifically splits a list into even and odd sets. However, the way your professor set up this code:
odd, even = foo([1,2,3,4,5,6], lambda x : x % 2 == 0)
Makes me believe they are attempting to get you to think a little more broadly by creating a function that accepts a list and a callback function (a simple True or False lambda function in this case) as arguments and returns the True/False lists.
Let’s start with the lambda function your professor gave and figure out what it’s doing:
splitter_function = lambda x: x % 2 == 0
# This has assigned the lambda function to the variable splitter_function so we can test it
# splitter_function accepts a number as an argument and returns True or False
# depending on if the number is even (True) or odd (False)
print(splitter_function(5))
# False
print(splitter_function(4))
# True
Okay, so knowing that, we need a function foo()
that accepts a list of numbers and applies a True/False callback function to each number then appends them to an appropriate list for return.
def foo(list_of_numbers, splitter_function):
"""Function that accepts a list of numbers and splits them into
truthy and falsy lists based upon the callback function argument"""
f = [] # Falsy list
t = [] # Truthy list
for number in list_of_numbers:
if splitter_function(number):
t.append(number)
# If splitter_function returns True --> append number to list t
else:
f.append(number)
# Else if splitter_function returns False --> append number to list f
return (f, t) # Return the lists, Falsy (odd potentially) first, then Truthy (even potentially)
Now to use it:
print(foo([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0))
# ([1, 3, 5], [2, 4, 6])
odd, even = foo([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0)
print(odd)
#[1, 3, 5]
print(even)
# [2, 4, 6]
# This can also be used to check if numbers are divisible by numbers other than 2 as well
not_divisible, divisible = foo([1, 2, 3, 4, 5, 6], lambda x: x % 3 == 0)
print(not_divisible)
# [1, 2, 4, 5]
print(divisible)
# [3, 6]
Hope that helps.