[Edu-sig] What version of Python to teach ....
John Zelle
john.zelle at wartburg.edu
Mon Apr 20 02:55:20 CEST 2009
Hi,
On Sunday 19 April 2009 18:44:30 michel paul wrote:
> On Sun, Apr 19, 2009 at 2:48 PM, Gregor Lingl <gregor.lingl at aon.at> wrote:
> > >How do you explain the nature of range to beginners?
>
> How about using list(range())? Something like:
> >>> # Here's how you can create a list of integers:
> >>> list(range(10))
>
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> >>> list(range(1, 10))
>
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> >>> list(range(1, 10, 2))
>
> [1, 3, 5, 7, 9]
>
> >>> list(range(-10, 10, 2))
>
> [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8]
>
> >>> # 'list' creates a list, and 'range' specifies its starting point,
>
> ending point, and interval between points.
I would say that the range specifies the sequence of objects that the list is
created from. I agree that using list is a good way to approach this.
> >>> # a range object produces these values when called upon to do so.
> >>> # for example, in a loop:
> >>> for x in range(10): (x, x**2)
>
> (0, 0)
> (1, 1)
> (2, 4)
> (3, 9)
> (4, 16)
> (5, 25)
> (6, 36)
> (7, 49)
> (8, 64)
> (9, 81)
>
> Now, interesting, here I've stumbled on a question that I need some
>
> clarification on:
> >>> a = range(10)
> >>> type(a)
>
> <class 'range'>
>
> >>> next(a)
>
> Traceback (most recent call last):
> File "<pyshell#49>", line 1, in <module>
> next(a)
> TypeError: range object is not an iterator
>
> >>> help(range)
>
> Help on class range in module builtins:
>
> class range(object)
>
> | range([start,] stop[, step]) -> range object
> |
> | Returns an iterator that generates the numbers in the range on demand.
>
> So is range an iterator?
No, a range object is not itself an iterator. It is an object that returns an
iterator when you ask it for one. You can create any number of independent
iterators from a single range object:
>>> x = range(1,10)
>>> it1 = iter(x)
>>> >>> next(it1)
1
>>> next(it1)
2
>>> it2 = iter(x)
>>> next(it2)
1
>>> next(it2)
2
>
A for loop always "asks" the sequence object for its iterator. If you want to
loop over a collection object, it should implement the __iter__ hook that
produces and iterator object. It is the iterator object that implements the
__next__ hook.
Of course, the usual approach is to use a generator method (uses yield) which
itself hands back an iterator when it is "called."
--John
--
John M. Zelle, Ph.D. Wartburg College
Professor of Computer Science Waverly, IA
john.zelle at wartburg.edu (319) 352-8360
More information about the Edu-sig
mailing list