Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*args returns a list containing only those arguments that are even

I'm learning python and in an exercise I need to write a function that takes an arbitrary number of arguments and returns a list containing only those arguments that are even.

My code is wrong I know: (But what is wrong with this code ?)

def myfunc(*args):
    for n in args:
        if n%2 == 0:
            return list(args)
myfunc(1,2,3,4,5,6,7,8,9,10)
like image 268
Aarón Más Avatar asked Jan 28 '23 03:01

Aarón Más


2 Answers

Do a list-comprehension which picks elements from args that matches our selection criteria:

def myfunc(*args):
    return [n for n in args if n%2 == 0]

print(myfunc(1,2,3,4,5,6,7,8,9,10))
# [2, 4, 6, 8, 10]
like image 80
Austin Avatar answered Feb 02 '23 01:02

Austin


This also could be helpful, however, the previous comment looks more advanced:

def myfunc(*args):
    lista = []
    for i in list(args):
        if not i % 2:
            lista.append(i)
    return lista
like image 40
mahyar khatiri Avatar answered Feb 02 '23 01:02

mahyar khatiri