transform list of int in a list of string??

Peter Hansen peter at engcorp.com
Fri Sep 13 21:28:32 EDT 2002


jubafre at brturbo.com wrote:
> my program have other modules imported, like re and sre and i put a convertion int to str but doesn´t work
> t=str(x[i])
> Traceback (most recent call last):
>   File "C:\Documents and Settings\jubafre\Desktop\montador\teste.py", line 78, in ?
>     t=str(x[i])
> TypeError: 'list' object is not callable

This error is most likely because you created a list object
bound to the name "str".  Do *not* use "str" or other such
reserved names as variable names if you want to preserve your
sanity. :-)

> Why i can´t transform a int number in string in my program???
> I tryed with import string, and can´t too, 
> but if i start a new python shell it works, why??

Because when you restarted Python the new session did not have
the variable called "str".

>>>>x=[1,2,3,4,]
>>>>s=[]
>>>>for i in range(len(x)):
> 	t=str(x[i])
> 	s.append(t)
>>>>print s
> ['1', '2', '3', '4']

By the way, although this code works, it is not at all what we
would call "Pythonic".  It looks like code from some other
language translated to Python.  For example, in Python you
don't need to (and rarely want to) use index variables to
iterate through a list like that: you can directly iterate
on the list items like this:

 >>> x = [1, 2, 3, 4]
 >>> s = []
 >>> for item in x:
...     s.append(str(item))
...
 >>> print s
['1', '2', '3', '4']

Note though that there are two tools for doing this kind of
thing much more easily, as shown in the postings by Skip Montanaro
or Erik Max Francis.  The "map" method is older but has advantages
in certain circumstances, while the other method is called a
"list comprehension" and can be both more readable and faster,
again depending on circumstances.

In general, there are a lot of Python idioms which work in a
similar fashion, going in ways traditional languages have not.
They're well worth watching for and learning.  (But your code
has one strong point in its favour, for a newbie: it works! :-)

-Peter




More information about the Python-list mailing list