How do I get the last number in a list that is very large?

Question:

def fib(n):
    a=0
    b=1
    for i in range(n+1):
        yield a
        a,b = b,a+b

lastnum = [num for num in fib(150000)]
lastnum[-1]

This is about the largest number (150000th number in fib) I can get from this method (Memory Error if larger). Is there ways I can improve this to get up to 2,000,000th digit? Is there a way to loop ‘del’ in my range loop till the last number needed in order to keep memory free by not saving EVERY number before?

tried a complicated mess of looping del and it was throwing errors or giving unexpected outputs

sorry kinda new to python

Thanks!

Asked By: ValdeVox

||

Answers:

If you really only want the last element, then just avoid using a list in the first place. For instance, the following took some time but didn’t run into any memory issues:

i = 2000000
for n in fib(i):
    result = n
print(result)

If, however, you want something more general (such as getting the last k elements or something), then you can use itertools.islice.
Here’s the usage for getting the last element as requested, but you can tweak this to get other "slices" as necessary:

from itertools import islice
i = 2000000
print(list(islice(fib(i), i, i + 1))[0])

Docs: https://docs.python.org/3/library/itertools.html#itertools.islice

Answered By: ShlomiF
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.