Getting "TypeError:list indices must be integers"

John Machin sjmachin at lexicon.net
Tue Jun 13 02:46:02 EDT 2006


On 13/06/2006 4:11 PM, Girish Sahani wrote:
> Hi,
> Please check out the following loop,here indexList1 and indexList2 are a
> list of numbers.

Later you say they are integers. Note: Python calls 2.0 a float, not an 
integer.
|>>> foo = [9, 8, 7]
|>>> foo[2.0]
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: list indices must be integers
|>>>

> 
> for index1 in indexList1:
>   for index2 in indexList2:
>     if ti1[index1] == ti2[index2] and not index1 != indexList1.pop():

Wouldn't
     ... and index1 == indexList1.pop()
be easier to follow?

Didn't I read earlier today somebody being admonished for modifying a 
list over which they were iterating? Who was that? You! What do you 
think indexList1.pop() is doing???

>        index1+=1
>        index2+=1

The above 2 statements have no effect at all. In particular, they 
*don't* affect the next value used by the relevant for statement, if 
that's what you were hoping for.

>        continue
>     elif index1 == indexList1.pop() and charList in pairList:
>        k = string2.index(char2[0])
>        instance = ti2(k)
>        tiNew = ti1.append(instance)
>        tiNewList.append(tiNew)
>     else:
>        break
> 
> On running my program, python gives me a TypeError saying:
> 
>    if ti1[index1] == ti2[index2] and not index1 != indexList1.pop():
> TypeError: list indices must be integers
> 
> Even though index1 and index2 are really integers.Please help!

How do you know that they are integers? Have you followed the advice 
given by readers of previous episodes of your adventures, and inserted 
print statements at relevant points?

In this case, inserting
     print repr(index1), repr(index2)
immediately after the 2nd for statement would be a very good idea.

Please do come back and tell us what you find out, *and* what you have 
learned.

HTH,
John



More information about the Python-list mailing list