[Python-ideas] Make len() usable on a generator

Nick Coghlan ncoghlan at gmail.com
Sat Oct 4 13:48:59 CEST 2014


On 4 October 2014 02:45, Ian Cordasco <graffatcolmingov at gmail.com> wrote:
> On Fri, Oct 3, 2014 at 11:32 AM, Alexander Belopolsky
> <alexander.belopolsky at gmail.com> wrote:
>> You are correct about python-ideas, but range is not a generator in python 3
>> either:
>>
>> Python 3.4.0a0 (default:e9cecb612ff7+, Oct  3 2014, 12:07:42)
>>>>> type(range(10))  # not a generator
>> <class 'range'>
>>>>> type(x for x in range(10))  # a generator
>> <class 'generator'>
>
> Ah yeah. All too often I conflate lazy iterators with generators. Nevermind

Python 3 range isn't a lazy iterator either - it's a full sequence
type (specifically, a calculated tuple:
https://docs.python.org/3/library/stdtypes.html#ranges). The only
immutable sequence operations it doesn't support are concatenation and
repetition (since concatenating or repeating a range can't be
represented using the simple "start + n*step" calculation that range
uses internally).

We'd have gotten a *lot* more complaints if we just dropped xrange in
as a substitute for the list objects returned by Python 2's range
builtin :)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list