Dilshad Abduwali
Dilshad Abduwali

Reputation: 1458

How to work around the limitation of `len` function in Python?

The len builtin function in Python is limited to the system's integer length. So, in my case, it is limited to sys.maxsize which is 2147483647. However, the in light with the Python3's unlimited integer, I think this limitation is causing frustration. Is there any workarounds to overcome this limitation? For example, I would like to get the length of this:

range(3, 100000000000000000000, 3)

But this:

len(range(3, 100000000000000000000, 3))

returns this error:

OverflowError: Python int too large to convert to C ssize_t

Upvotes: 3

Views: 522

Answers (2)

user2183078
user2183078

Reputation: 562

This seems like a bug in Python. At least for classes, you could replace

len(c)

with

c.__len__()

Upvotes: -1

Eevee
Eevee

Reputation: 48564

Unless you plan to have a plethora of lazily-iterable types with massive capacities, you could special-case range and do the math yourself:

def robustish_len(c):
    try:
        return len(c)
    except OverflowError:
        return (c.stop - c.start + c.step - 1) // c.step

Or, alternatively:

def robust_len(c):
    try:
        return len(c)
    except OverflowError:
        return float('inf')  # close enough  :)

Upvotes: 2

Related Questions