Search code examples
pythonpython-3.xmathinstance-variableslargenumber

Length of giant list-like objects in python


I'm creating a list-like object that holds a very large number of elements, however when I run the below code, I get an error.

class test:
    def __init__(self, n):
        self.n = n
        
    def __len__(self):
        return self.n
    
instance = test(10**20)
print(len(instance))

The error that I get back is: OverflowError: cannot fit 'int' into an index-sized integer

Anyone know what's going wrong?


Solution

  • This is a CPython implementation detail. From the __len__ docs:

    In CPython, the length is required to be at most sys.maxsize. If the length is larger than sys.maxsize some features (such as len()) may raise OverflowError. To prevent raising OverflowError by truth value testing, an object must define a __bool__() method.