On Sun, Apr 19, 2009 at 2:48 PM, Gregor Lingl <gregor.li...@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.
>>> # 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?

- Michel
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to