[Tutor] Difference between for i in range(len(object)) and for i in object

Jeff Shannon jeff at ccvcorp.com
Thu Dec 9 21:07:41 CET 2004

kumar s wrote:

  > Here is my code:

Create an empty list...

>>>>for m in cor:

Now, for each element in some other list from somewhere else,

> ...     cols = split(cor,'\t')

Ignore the element we've just isolated and try to split the entire 
list on '\t' ...

> Traceback (most recent call last):
>   File "<stdin>", line 2, in ?
>   File "/usr/local/lib/python2.3/string.py", line 121,
> in split
>     return s.split(sep, maxsplit)
> AttributeError: 'list' object has no attribute 'split'

Yup, the list 'cor' doesn't have a split() method.  The string that 
presumably should be in 'm' would have such a method, though.

> Here is 2nd way:
>>>>for m in cor:
> ...     cols = split(cor,'\t')

Once again, you're operating on the list, not the element of the list.

> Here is my 3rd way of doing this thing:
>>>>for m in range(len(cor)):
> ...     cols = split(cor[m],'\t')

Here, you *are* operating on an element of the list.  But if I were to 
write this segment to be parallel to your previous two attempts, it 
would be:

     cols = split(cor[cor],'\t')

which probably wouldn't surprise you when it doesn't work...

> My question:
>  Many people suggested me to avoid  iteration over  a
> object using (range(len)) its index and use instead
> 'Python's power' by using for i in object, instead. 
> However, when I tried that using some data, as
> demonstrated above, I get error because append method
> does not work on list.

No -- look carefully at the tracebacks, and you'll see that nowhere 
does it complain about append(), nor does it give the line numbers in 
which the append() takes place.  It complains about split(), and tells 
you exactly which line the problem is on ('File "<stdin>", line 2, in 
?' -- since you're doing this in an interpreter, there's no filename 
or function name).

Jeff Shannon
Credit International

More information about the Tutor mailing list