1

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!

2
  • 2
    You are never adding the values to the list, e.g. l.append(num). Note: don't use list as a variable name it hides python's list type. Commented Mar 20, 2019 at 3:05
  • Yes, I completely forgot that "list" was a reserved keyword as well as using the append method to add to a list... Commented Apr 2, 2019 at 2:18

2 Answers 2

1
def myfunc (*args):
    mylist = []
    for num in args:
        if num % 2 == 0:
            mylist.append(num)
    return mylist
Sign up to request clarification or add additional context in comments.

3 Comments

Much appreciated! Worked.
quick question, how did know that the return was supposed to line up with for and not if? Thank you!
It needs to line up with for since the return should happen only after the loop is completed. If it were lined up with if it would only make one pass though the loop.
1

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.

2 Comments

You may want to explain how yield num actually works. Remember, he/she is a newbie. (sorry for being annoying :P)
Note: list is not a reserved keyword or you wouldn't be able to hide it with a variable, it is a builtin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.