I am out of trial and error again Lists

Terry Reedy tjreedy at udel.edu
Fri Oct 24 05:14:37 CEST 2014

On 10/23/2014 3:39 PM, Ian Kelly wrote:
> On Thu, Oct 23, 2014 at 11:07 AM, Seymore4Head
> <Seymore4Head at hotmail.invalid> wrote:
>> BTW I forgot to add that example 2 and 3 don't seem to be too useful
>> in Python 3, but they are in Python 2.  I don't understand how the
>> Python 3 is an improved version.
> In Python 2, range returns a list containing all the requested
> elements. This is simple to work with but often not desirable, because
> it forces the entire sequence to be loaded into memory at once. Large
> ranges may cause excessive memory use and related slowdowns, while
> very large ranges may not even be usable.
> In Python 3, range returns a compact object that knows what elements
> it contains and can iterate over them (which is the most common use of
> ranges by far), but without needing to load them all into memory at
> once. While iterating, only the current element needs to exist in
> memory. You can still get the range as a list if you want it, by
> calling list(range(10)), but it doesn't force you to create a list,
> which makes it more versatile than the Python 2 construct.
> The more specialized data structure used in Python 3 also allows for
> certain optimizations, for example membership testing. In Python 2, if
> you do the test "97 in range(100)", it has to construct a 100-element
> list and then iterate over 97 of the elements before discovering that
> the list does in fact contain the number 97. The Python 3 range object
> knows what the bounds of the range are, so all it has to do is check
> that 0 <= 97 < 100 to know that the number 97 is included in the
> range.

Example that works 'instantly' in 3.x, but would be slightly insane in 
2.x, even if you have enough memory for it to work on a 64 bit build.

 >>> r =range(0, 1000000000000000, 999937)
 >>> 3428761974385 in r
 >>> 3428761974386 in r

Terry Jan Reedy

More information about the Python-list mailing list