-2

I was trying to use *args with a for loop in python, however I don't see how to return all the values passed to the function, which should return all the even numbers

def f_even(*args):
    for item in args:
        if item%2 == 0:
            return item

The above code returns only the first value, as I guess after the return it goes out of the function. Indeed, if I use print instead, it works

I'm trying to find a way to return a tuple with all the even numbers when I pass let's say (1,2,3,4,5) to the function

Thank you!

Milo Bem
  • 1,033
  • 8
  • 20
ChrisA
  • 81
  • 11
  • 2
    So, return a tuple? `return x, y` is perfectly valid. Having a `return` inside a `for` loop, though, probably isn't what you wanted. `return` will immediately break you out of the function. – roganjosh Dec 08 '18 at 19:01
  • 2
    You should read https://docs.python.org/3/tutorial/datastructures.html and learn to use lists. – Jim Stewart Dec 08 '18 at 19:01
  • 2
    You can, for example, store the values to be returned in a list, then return the list. If you're feeling adventurous, it may be time to learn about generators! – ForceBru Dec 08 '18 at 19:01
  • Perhaps you should look into [generators](https://wiki.python.org/moin/Generators) and the [`yield`](https://docs.python.org/3/reference/simple_stmts.html#the-yield-statement) statement? – Some programmer dude Dec 08 '18 at 19:04

3 Answers3

1

In python you can use list comprehension to do this. will make you code more readable and will shrink it too.

def f_even(*args):
   return [elem for elem in args if elem % 2 == 0]
Gaurang Shah
  • 11,764
  • 9
  • 74
  • 137
0

You could slightly modify you function and make it a generator by using yield. This way your function wont end after returning first even number but will keep yielding them one by one.

def f_even(*args):
    for item in args:
          if item%2 == 0:
             yield item

for i in f_even(1,2,3,4,5):
    print(i)

Output:

2
4

Or if you want to store all yielded values:

even_numbers = list(f_even(1,2,3,4,5))
print(even_numbers) # -> [2, 4]
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
-1

Done, thank you all!!

def f_even(*args): mylist = [] for item in args: if item%2 == 0: mylist.append(item) return mylist

ChrisA
  • 81
  • 11