Christelle
Christelle

Reputation: 35

Python Function To Return List

Python newbie here.I wrote this function to only return even numbers as a list but I am failing at doing this. Can you please help? This is my initial function which works fine but results are not coming out as a list:

def myfunc (*args):
    for num in args:
        if num % 2 == 0:
            print (num)

When you call the function for example with the following arguments:

myfunc(1,2,3,4,5,6,7,8,9,10)

I am getting:

2
4
6
8
10

but I need those to be in a list, what am I missing? This doesn't work either:

list = []
def myfunc (*args):
    for num in args:
        if num % 2 == 0:
            print (list[num])

Much appreciated!

Upvotes: 1

Views: 8769

Answers (2)

knh190
knh190

Reputation: 2882

Your function is not returning anything. You may want to get the elements by

def myfunc (*args):
    for num in args:
        if num % 2 == 0:
            yield num

Or create a temporary list:

def myfunc (*args):
    lst = []
    for num in args:
        if num % 2 == 0:
            lst.append(num)
    return lst

You can check your returned value in REPL:

>> type(print(num)) # print() returns None
NoneType

Explanation: In short, yield returns an element per time the function is iterated - and only returns an element once. So the function is also called a "generator". There is an excellent post about yield. I cannot explain better than it.


Update: Don't use list as variable name, list is a builtin method.

Upvotes: 1

davejagoda
davejagoda

Reputation: 2528

def myfunc (*args):
    mylist = []
    for num in args:
        if num % 2 == 0:
            mylist.append(num)
    return mylist

Upvotes: 1

Related Questions