[Tutor] lists

Kent Johnson kent37 at tds.net
Tue Feb 14 16:34:27 CET 2006


Michael Haft wrote:
> 
> 
> Hello,
>         I have a list of 15 str values called p, when I try the following code:
> 
> for x in p:
>      p[x] = float(p[x])/10
> print p

The problem is that iterating a list yields the actual values in the 
list, not the indices to the list:
  >>> p = ['1900', '51.50', '11.50']
  >>> for x in p:
  ...   print x
  ...
1900
51.50
11.50

The above are string values though you can't tell from the print. 
Indexing p by a string gives the error you saw:

  >>> p['1900']
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: list indices must be integers

One way to do what you want is to change the loop to iterate over 
indices of p rather than elements of p:
  >>> for i in range(len(p)):
  ...   p[i] = float(p[i])/10
  ...
  >>> print p
[190.0, 5.1500000000000004, 1.1499999999999999]

That works but it's not very Pythonic - there are better ways. For 
example the enumerate funcion yields pairs of (index, value) for each 
value in a list. It is handy when you need both the index and the value, 
as you do here:
  >>> p = ['1900', '51.50', '11.50']
  >>> for i, x in enumerate(p):
  ...   p[i] = float(x)/10
  ...
  >>> p
[190.0, 5.1500000000000004, 1.1499999999999999]

But even better is to use a list comprehension. This is a very useful 
Python construct that lets you build a new list from an existing list 
with a very elegant syntax:
  >>> p = ['1900', '51.50', '11.50']
  >>> p = [ float(x)/10 for x in p]
  >>> p
[190.0, 5.1500000000000004, 1.1499999999999999]

Kent



More information about the Tutor mailing list