[Tutor] append question

Rich Lovely roadierich at googlemail.com
Mon Jul 6 02:19:51 CEST 2009


2009/7/5 Steven Buck <buckstec at gmail.com>:
>>>> for i in len(test):
>             testvar2.append(test[i][2])
>
> I want testvar2 = [2,5,8] but instead I get the following error message:
>
> Traceback (most recent call last):
>   File "<pyshell#34>", line 1, in <module>
>     for i in len(test):
> TypeError: 'int' object is not iterable
>
> Any insight would be appreciated.
> Thanks
> Steve
> --
> Steven Buck
> Ph.D. Student
> Department of Agricultural and Resource Economics
> University of California, Berkeley

This sounds like a homework assignment, and we're not supposed to give
out answers to homework.

The error message and the docs explain what you're doing wrong if you
take a moment to look.
from http://www.python.org/doc/2.6/reference/compound_stmts.html#for

"""for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object. An iterator is created for the result of the expression_list.
The suite is then executed once for each item provided by the
iterator, in the order of ascending indices. Each item in turn is
assigned to the target list using the standard rules for assignments,
and then the suite is executed."""

As Luke said, len returns an int, which as your error tells you, is
not iterable.  From the same page:
"""The for statement is used to iterate over the elements of a
sequence (such as a string, tuple or list) or other iterable
object:"""

Therefore you have an iterable, there is no need to try and construct a new one.

Does that help?

It is extremly unpythonic to iterate over range(len(...)), as it adds
in the overhead of two function calls, and ruins the readability of
code.  The latter is probably the most important of the two.

An even more pythonic way to do this would be a list comprehension,
http://www.python.org/doc/2.6/tutorial/datastructures.html#list-comprehensions

If it's not homework, let us know, and we'll be more than willing to
give you code if you still need it.

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com


More information about the Tutor mailing list