Anthony
Anthony

Reputation: 1

Iterate through a newly generated list: Python

I am trying to reuse the newly created list from the Fibonacci sequence, I want to be able to use the answer to iterate through and call just the even numbers. I can do this on it's own but have no idea how to use the results of my current code. Any help greatly appreciated. Thank You.

FibStart = int(raw_input('Enter a start number : '))
FibStop = int(raw_input('Enter a stop number : '))
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-2) + fib(n-1)        
print map(fib, range(FibStart, FibStop))


# when called will return [0,1,1,2,3,5,8,13,21,34]

Upvotes: 0

Views: 59

Answers (1)

abarnert
abarnert

Reputation: 365697

Just translate your English text into code:

I want to be able to use the answer

So store it in a variable:

answer = map(fib, range(FibStart, FibStop))

… to iterate through

So iterate through it:

for value in answer:

… and call just the even numbers.

So check if they're even:

    if value % 2 == 0:

Or, if you want to make a new list of just the even values to use repeatedly, you can use a list comprehension:

evens = [value for value in answer if value % 2 == 0]
for even in evens:

Upvotes: 7

Related Questions