0

So here I defined a function in python that tells if a given number is even or odd.

Now i want to create a list with the numbers in the result as its elemets, how is that possible?

def even_till_n(number):
     for in range(number+1): 
        if  (i%2 == 0):
             print(i)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
HusaynAly
  • 29
  • 6

2 Answers2

1

You need to create a list variable and append values to it. Then make your function return that list:

def even_till_n(number):
     result = list()
     for i in range(number+1): 
        if  (i%2 == 0):
             result.append(i)
     return result

# usage ...

test = even_till_n(10)
print(test)

# [0, 2, 4, 6, 8, 10]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Use a list-comprehension.

def even_till_n(number):
    return [x for x in range(number+1) if x%2 == 0]
rdas
  • 20,604
  • 6
  • 33
  • 46
  • List-comprehensions are a feature of python: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python they follow are used to create lists from other iterables – rdas Jun 11 '19 at 17:02
  • 1
    If the OP doesn't even understand how construct a list, perhaps throwing a list comprehension at them isn't very helpful pedagogically. – juanpa.arrivillaga Jun 11 '19 at 17:10