Search code examples
pythonvariadic-functionskeyword-argument

*args returns a list containing only those arguments that are even I tried in two ways but still I am getting the same error


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

This is what I tried:

def myfunc(*args):
     for n in args:
         if n%2 == 0:
             return list(args)
             
print(myfunc(1,2,3,4,5,6,7,8,9))   

error:

Error details
Lists differ: [-2, 4] != [-1, -2, 4, 3, 5]

First differing element 0:
-2
-1

Second list contains 3 additional elements.
First extra element 2:
4

- [-2, 4]
+ [-1, -2, 4, 3, 5] : This is incorrect  

I want to understand the error


Solution

  • There are a couple things wrong with your function. First, when I run your code I do not get that error. I get the list that was inputted. It also looks like you are using a testing framework. If you want to get a list of args that are even, you can do this efficiently with list comprehension:

    >>> args = [1,2,3,4,5,6,7,8,9,10]
    >>> output = [arg for arg in args if arg%2 == 0]
    >>> print(output)
    [2, 4, 6, 8, 10]
    

    You are also returning the entire list of args if one of the elements is even. The function will terminate after the first even element. If you want to do it in a function, return the list after you have iterated through all the elements.

    >>> def myfunc(*args):
    ...     result = []
    ...     for arg in args:
    ...         if arg%2 == 0:
    ...             result.append(arg)
    ...     return result
    ...
    >>> print(myfunc(1,2,3,4,5,6,7,8,9,10))
    [2, 4, 6, 8, 10]