[Tutor] list semantics
Steven D'Aprano
steve at pearwood.info
Sat Apr 11 21:09:43 CEST 2015
On Sat, Apr 11, 2015 at 02:15:49PM -0400, Joel Goldstick wrote:
> On Sat, Apr 11, 2015 at 1:41 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> > Why does the first range convert to a list, but not the second?
> >
> >>>> p = list(range(1,20)), (range(40,59))
> >>>> p
> > ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
> > range(40, 59))
> >
> Assuming you are using python 3.x range is a generator, so it only
> produces values if you iterate over it
Almost correct, but not quite. range, like xrange in Python 2, is not a
generator, but a custom-made lazy sequence object.
py> gen() # This actually is a generator.
<generator object gen at 0xb7bd7914>
py> range(1, 10) # This is not.
range(1, 10)
Range objects are special: not only do they produce values lazily as
needed, but they also support len(), indexing, slicing, and membership
testing, none of which generators are capable of doing:
py> r = range(1, 30, 3)
py> len(r)
10
py> r[8] # indexing
25
py> r[2:5] # slicing
range(7, 16, 3)
py> 9 in r # membership testing
False
py> 10 in r
True
All those results are calculated lazily, without having to pre-calculate
a potentially enormous list.
--
Steve
More information about the Tutor
mailing list