Find the next Fibonacci number This code calculates, from a list of integers, the next fibonacci number for each integer. It does this for the first 60 numbers in the sequence. Any pointers on improving computing time, code readability, etc. are what I'm looking for.

def getFib(limit):
    a = 1
    b = 1
    res = [a, b]

    for i in range(1, limit):
        temp = a
        a = b
        b = temp + b
        res.append(b)
    return res

def nextFibonacci(fib, n):

    for x in n:
        if x &lt; 1 or x &gt; fib[len(fib)-1]:
            print("Value is out of range.")
        else:
            temp = x

            for c in fib:
                if c &gt; temp:
                    temp = c
                    break

                print(temp)

def main():
    listMe = [1, 9, 22]
    fib = getFib(60)

    nextFibonacci(fib, listMe)

if __name__ == "__main__":
    main()
Use a cache to save fibonacci numbers, will improve speed of the program. That way you won't have to compute the numbers again at each loop.

'''
Cached_fib
'''
def memoize(f):
    cache = {}
    return lambda *args: cache[args] if args in cache else cache.update({args: f(*args)}) or cache[args]

@memoize
def fib(n):
    return n if n &lt; 2 else fib(n-2) + fib(n-1)

def find_closest_fib(l):
    for num in l: 
        i = 1
        while 2*num&gt;fib(i)+fib(i+1):
            i += 1
        print ('Nearest fib number = {} \n for num {}\n'.format(fib(i), num))


if __name__ == '__main__':
    l = (60, 234234231, 35342454, 27000000000000)
    start_time = timeit.default_timer()
    find_closest_fib(l)
    print('Elapsed time: ', timeit.default_timer() - start_time)

    start_time = timeit.default_timer()
    find_fib_op(l)
    print('Elapsed time: ', timeit.default_timer() - start_time)




Output new version

Nearest fib number = 55 for num 60
Nearest fib number = 267914296 for num 234234231
Nearest fib number = 39088169 for num 35342454
Nearest fib number = 27777890035288 for num 27000000000000




Timing of implementation

Cached fibonacci


  Elapsed time: 0.06364319414684597


OP fibonacci


  Elapsed time: 0.23451719927193976