PEP 276 -- What else could iter(5) mean?

James_Althoff at i2.com James_Althoff at i2.com
Mon Mar 4 16:44:33 EST 2002


Not clumsy at all.  I like your rewording!

Jim

=============================

Jeremy Cromwell wrote: >>>>>>>>>>>

Without trotting out ugly examples, it is cleaner than many of the current
features in python.  I'm still a relative newbie, but I remember it being a
bit jarring to need to use range() just to iterate through numbers.

It's so simple to explain and understand, that I doubt that it would be
confusing.  Here's my clumsy rewording of the tutorial:

4.3 For x in integer, and the range() Function
When given an integer rather than a sequence, the for statement iterates
over the numbers from 0 up to (but not including) the given number:

>>> for i in 3:
...     print i, i*3
0, 0
1, 3
2, 6

The given end point is never part of the generated list; for x in 10
iterates through a list of 10 values, exactly the legal indices for items
of
a sequence of length 10.

To iterate over the indices of a sequence, use len() as follows:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in len(a):
...     print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb


If you do need to iterate over a more complex sequence of numbers, the
built-in function range() comes in handy. It generates lists containing
arithmetic progressions.  You supply the start and finish and it produces a
list from start up to finish, incrementing by one:

>>> range(5, 10)
[5, 6, 7, 8, 9]

It is possible to specify a different increment (even negative; sometimes
this is called the `step'):

>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]

Calling range() with one number produces the same list that a for statement
iterates over for that number:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

--- end tutorial ---

I like this proposal and would like to see it adopted.  If others like it,
they should speak up since about all we hear from are the detractors.

Jeremy Cromwell

...now let's see..<PrtScnSysRq>...<PgUp>...Hmmm, where's that <wink> key?

<<<<<<<<<<<<<<<<<<<<<






More information about the Python-list mailing list