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

Question:

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)
Asked By: Aarón Más

||

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]
Answered By: 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
Answered By: mahyar khatiri

Pick evens

def myfunc(*args):
    abc = []
    for n in args:
        if n%2==0:
            abc.append(n) 
    return abc
Answered By: Sanket Patil
def myfunc(*args):
    x=[]
    for i in list(args):
        if i%2==0:
            x.append(i)
    return x
Answered By: naruto
def myfunc(*args):
    mylist = []
    for x in list(args):
        if x % 2 == 0:
            mylist.remove(x)
    return mylist
Answered By: Nahean Islam
def myfunc(*args):
    even=[]
    for n in args:
        if n %2==0:
            even.append(n)
        else:
            pass
        
    return even
myfunc(1,2,3,4,8,9)
Answered By: Mr.Monk
def myfunc(*args):
    #solution 1
    # Create an empty list
    mylist = []
    for number in args:
        if number %2 == 0:
            mylist.append(number)
        else:
            pass
    # return the list
    return mylist
    
    #solution 2
    # Uses a list comprehension that includes the logic to find all evens and the list comprehension returns a list of those values
    # return [n for n in args if n%2 == 0]
Answered By: Jay

You need to create an empty list to contain the even numbers. Also convert your arguments to a list. Then append the even numbers to the newly created list.

def myfunc(*args):
new_list = []
for num in list(args):
    if num % 2 == 0:
        new_list.append(num)
else:
    pass
return new_list 
Answered By: Moses
def myfunc(*args):
    return [x for x in args if not x&1]
Answered By: pham tan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.