'How return a list of even arguments in python?

Define a function called myfunc() which takes an arbitrary and returns a list of arguments if the arguments are even. below is the code i"ve written

def myfunc(*args):
    if args%2==0:
        return list(args)
    else:
        pass

and the error is:

unsupported operand type(s) for %: 'tuple' and 'int'

but i can't find error in my code.

please help!!



Solution 1:[1]

*args is a tuple of arguments. You can't using modulo on it directly. Also you should always return something in all cases if you return something at all.

This will return the arguments in a list if an even number of arguments are passed:

def myfunc(*args):
    if len(args) % 2 == 0:
        return list(args)
    return None

This will return only arguments that are even:

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

Solution 2:[2]

If you need all args to be even then you can try:

def myfunc(*args):
    # Check all args are ints. Could allow other types if needed
    if not all([isinstance(a, int) for a in args]):
        return
    if all([a%2 == 0 for a in args]):
        return list(args)
    return 

This gives the following:

myfunc(2,4,'a',8)
> None
myfunc(2,4,6,8)
> [2,4,6,8]
myfunc(2,4,5,8)
> None

Solution 3:[3]

def is_even(*args):
    is_even_new = []
    for num in args:
       if num % 2 == 0:
          is_even_new.append(num)
       else:
          pass
    return is_even_new

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Error - Syntactical Remorse
Solution 2 PyPingu
Solution 3