简体   繁体   中英

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM