Robi
Robi

Reputation: 11

*args returns a list containing only even arguments (Python)

Hi I am trying to return all items which are even, but it returns only first even number from the list.

def myfunc (*args):
   for item in args:
       if item%2==0:
            return item
myfunc(5,2,6,8)

out 2

Upvotes: 0

Views: 249

Answers (4)

user
user

Reputation: 7604

You should add to a list instead of using a return statement. What you can do is filter using a lambda:

def myfunc (*args):
  return list(filter(lambda x : x % 2 == 0, args))
print(myfunc(5,2,6,8))

Upvotes: 0

VPfB
VPfB

Reputation: 17267

You could also use the built-in filter function designed for general use. Just add a test, in your case a test for being even. The function returns an iterator. If you want to save the data, create e.g. a list.

>>> inp = (1,2,3,4,5,6)
>>> list(filter(lambda x: x%2==0, inp))
[2, 4, 6]

Upvotes: 0

sandeshdaundkar
sandeshdaundkar

Reputation: 903

Please change your function, return stops the execution of the function. Currently in your code, you just check if an element is even number and return that, which stops iterating further in the list. You will have to save it in a list and either return the list or print each item in the list. Change your code as below.

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

myfunc(5,2,6,8)

Here we are using a list comprehension to save even numbers in a list and iterating over the list of even numbers to print them. You can also return even_nums insted of iterating over.

Upvotes: 0

Leo Arad
Leo Arad

Reputation: 4472

You can do

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

This code will return you all the even numbers for the myfunc params like

myfunc(2,3,4,5)

Return

[2, 4]

Upvotes: 3

Related Questions