[Python-ideas] Pass a function as the argument "step" of range()
Nick Coghlan
ncoghlan at gmail.com
Mon Jul 6 07:17:13 CEST 2015
On 6 July 2015 at 15:00, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> At any rate, as I'm sure you know, that works in 1.5.2 because range returns
> a list. Try it with range(1000000000) and you may not be quite as happy with
> the result--but in 3.2+, it returns instantly, without using more than a few
> dozen bytes of memory.
One kinda neat trick with Python 3 ranges is that you can actually
work with computed ranges with a size that exceeds 2**64 (and hence
can't be handled by len()):
>>> 50 in range(-10**1000, 10**1000)
True
>>> len(range(-10**1000, 10**1000))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C ssize_t
Conveniently, this also means attempting to convert them to a concrete
list fails immediately, rather than eating up all your memory before
falling over.
Those particular bounds are so large they exceed the range of even a C double:
>>> float(10**1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list