python for loop

Ben Finney ben+python at benfinney.id.au
Tue Mar 31 20:42:20 EDT 2009


Lada Kugis <lada.kugis at gmail.com> writes:

> in python for example:
> for i in range(1,n)
> goes from 1,2,3,4,...,n-1
> (that is, it goes from 1 up to, but not including n)

Also, ‘range(n)’ counts from 0 to n-1.

> Why is that so ?

The answer is in the documentation for ‘range’:

    For example, range(4) returns [0, 1, 2, 3]. The end point is
    omitted! These are exactly the valid indices for a list of 4
    elements.

You may be interested in the iterator-generating functions in 
‘itertools’ <URL:http://docs.python.org/library/itertools>.

-- 
 \          “Our products just aren't engineered for security.” —Brian |
  `\             Valentine, senior vice-president of Microsoft Windows |
_o__)                                                      development |
Ben Finney



More information about the Python-list mailing list