Search code examples
pythonargs

What is the reason behind args() returning only one value when return() method is used?


The code that I am using is below:

def myfunc(*args): for i in (args): if i % 2 == 0: return i

myfunc(1,2,3,4,5,6)

Current Output is:

Output : 2

Expectation: I would like to return all the even values instead of just one value alone.


Solution

  • You are returning the 1st value that satisfies the if condition. You need to store all the values in list then return after for loop is completed.

    def func(*args):
        temp = []
        for i in (args):
            if i%2==0:
                temp.append(i)
        return temp
    
    print(func(1,2,3,4,5,6))
    

    Output:

    [2,4,6]