python for loop

Chris Rebert clp2 at rebertia.com
Tue Mar 31 20:39:42 EDT 2009


On Tue, Mar 31, 2009 at 5:24 PM, Lada Kugis <lada.kugis at gmail.com> wrote:
> I'm coming from fortran and c background so I'm certainly biased by
> them. But if you could explain one thing to me:
>
> in fortran for example:
> for i=1,n
> goes from 1,2,3,4,...,n
>
> 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)
>
> Why is that so ? What were the reasons for that "not including" part ?
> It troubles me greatly, and I cannot see it's advantages over the
> "standard" "up to and including" n.

Because it's extremely handy when the list variable is a list index:

my_list = [1,2,3,4]
for i in range(len(my_list)):
    #i goes from 0 to len(my_list)-1, which is all the indices of the list
    print my_list[i]

Of course, this is a toy example which would be better written `for i
in my_list:`, but you get the point.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-list mailing list