# Is_even - running function with a list

#1

Exercise:

is_even
All right! Let’s get started.

I completed the exercise, but would like to understand it better by feeding a list into the function.

The code below works for one value. When a value is 40 it prints TRUE.

``````# z = [1, 2, 3]

def is_even(x):
if  x % 2 == 0:
return True
else:
return False

print (is_even(40))
``````

But I am not sure how to use a list. Please point me in the right direction.

I tried below code

``````z = [1, 2, 3]

def is_even(x):
if  x % 2 == 0:
return True
else:
return False

print (is_even(z))
``````

which gave me an error

``````Traceback (most recent call last):
File "python", line 9, in <module>
File "python", line 4, in is_even
TypeError: unsupported operand type(s) for %: 'list' and 'int'
``````

Not sure how to iterate over the list.

#2

Iterate over the list, and compose a new list of the results.

``````>>> def is_even(x):
return [not n % 2 for n in x]

>>> print (is_even([1,2,3]))
[False, True, False]
>>>
``````

That’s the more advanced approach though you might not be familiar with it since the concept of list comprehensions does not come up until the Advanced Topics in Python unit.

Try setting up a loop to iterate over the inputs, then append the result of the test to the list.

``````result = []
for item in x:
if item % 2 == 0:
outcome = True
else:
outcome = False
result.append(outcome)
return result``````

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.