Python: TypeError: list indices must be integers, not list

Python: TypeError: list indices must be integers, not list

Pythons for loop is not indexed-based, it really iterates on the sequence (or any iterable). So in this code:

for whatever in some_iterable:
    do_something_with(whatever)

whatever is successively bound to each item in some_iterable. As an example:

>>> mylist = [A, B, C]
>>> for item in mylist:
...     print item is, item
... 
item is A
item is B
item is C

If you want the indexes to, you can use the builtin enumerate(iterable, start=0) function, which yields a (index, item) tuple for each item in iterable:

>>> for index, item in enumerate(mylist):
...     print item %s is %s % (index, item)
... 
item 0 is A
item 1 is B
item 2 is C

You are indexing your lists with a non-int type index:

for count in list_kp2_ok:
    for count1 in list_kp2_2_ok:
        if list_kp2_ok[count]==list_kp2_2_ok[count1]:

So a quick fix for that is to do it this way:

for coord1 in list_kp2_ok:
    for coord2 in list_kp2_2_ok:
        if coord1==coord2:

You can even do the whole coding in one statement:

list_wsp=[coords for coords in list_kp2_ok if coords in list_kp2_2_ok]

This will directly output to you the common coordinates in both lists.

Python: TypeError: list indices must be integers, not list

You can use list comprehension:

new_list = [i for i in list_kp2_ok if i in list_kp2_2_ok]

Leave a Reply

Your email address will not be published. Required fields are marked *