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!

user2357112
  • 260,549
  • 28
  • 431
  • 505
Christelle
  • 35
  • 1
  • 7
  • 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. – AChampion Mar 20 '19 at 03:05
  • Yes, I completely forgot that "list" was a reserved keyword as well as using the append method to add to a list... – Christelle Apr 02 '19 at 02:18

2 Answers2

1
def myfunc (*args):
    mylist = []
    for num in args:
        if num % 2 == 0:
            mylist.append(num)
    return mylist
davejagoda
  • 2,420
  • 1
  • 20
  • 27
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.

knh190
  • 2,744
  • 1
  • 16
  • 30
  • 2
    You may want to explain how `yield num` actually works. Remember, he/she is a newbie. (sorry for being annoying :P) – slackmart Mar 20 '19 at 03:11
  • 1
    Note: `list` is not a reserved keyword or you wouldn't be able to hide it with a variable, it is a builtin. – AChampion Mar 20 '19 at 03:12