python for loop
Arnaud Delobelle
arnodel at googlemail.com
Wed Apr 1 17:32:37 EDT 2009
Lada Kugis <lada.kugis at gmail.com> writes:
> 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.
>
> Best regards
> Lada
Luckily Python allows you to create your own indexing on lists:
def dec(i):
if isinstance(i, slice):
return slice(dec(i.start), dec(i.stop), i.step)
elif i is None or i < 0:
return i
else:
return i - 1
defop = """
def __%sitem__(s,i,*r):
val = list.__%sitem__(s,dec(i),*r)
if isinstance(i, slice): val = List1(val)
return val
def __%sslice__(s,i,j,*r):
return List1(list.__%sslice__(s,dec(i),dec(j),*r))
"""
class List1(list):
for op in 'del', 'get', 'set':
exec defop % (op, op, op, op)
def index(self, x):
return list.index(self, x) + 1
def insert(self, i, x):
list.insert(self, dec(i), x)
def pop(self, i=None):
return list.pop() if i is None else list.pop(dec(i))
for op in 'add', 'mul', 'radd', 'rmul':
exec "def __%s__(*r): return List1(list.__%s__(*r))" % (op, op)
l1 = List1(range(10))
l2 = List1("Python rules")
I'll let you play with l1 and l2.
--
Arnaud
PS. What day is it again?
More information about the Python-list
mailing list