PEP 276 -- What else could iter(5) mean?
jcromwell at ciena.com
Sun Mar 3 01:53:10 CET 2002
If python was to allow "for i in 5:", is there any other meaning that would
be appropriate besides the one detailed in PEP 276?
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
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]
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:
[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.
...now let's see..<PrtScnSysRq>...<PgUp>...Hmmm, where's that <wink> key?
More information about the Python-list