TypeError: 'int' object is not subscriptable on lists of different sizes

Viewed 228

I am trying to print the common items in two list of lists with different sizes, but I am getting the following error. TypeError: 'int' object is not subscriptable

These are the lists

lst1 = [[1234, John Paul, New York], [4567, Jude Law, London],[7891, Rick Ross, Miami]]
lst2 = [[1234, John Paul, New York], [7891, Rick Ross, Miami]]

This is my function which is looping through the list and trying to find the common items and put them into a new list.

lst1 = [[1234, John Paul, New York], [4567, Jude Law, London],[7891, Rick Ross, Miami]]
lst2 = [[1234, John Paul, New York], [7891, Rick Ross, Miami]]
list = []
min_lengh = min(len(lst1), len(lst2))
max_lengh = max(len(lst1), len(lst2))

for i in range(max_lengh):
    if lst1[i[0] % min_lengh] == lst2[i[0] % min_lengh]:
        list.append(i % min_lengh)
return list

So I am checking if the first items in the list match, if they do then add them to the list.

The line which is throwing the error is this.

if lst1[i[0] % min_lengh] == lst2[i[0] % min_lengh]:

What am I doing wrong?

4 Answers

i is not an element in the list, it's an index: 0, 1, 2, ... So i[0] makes no sense.

You probably meant lst1[i % min_lengh][0]: first get the sub-list (such as [1234, John Paul, New York]), then get the first element from that sub-list (such as 1234).

Your solution has some issues to run through both the list . here is the working solution

lst1 = [[1234, 'John Paul', 'New York'], [4567, 'Jude Law', 'London'],[7891, 'Rick Ross', 'Miami']]
lst2 = [[1234, 'John Paul', 'New York'], [7891, 'Rick Ross', 'Miami']]
list = []
min_lengh = min(len(lst1), len(lst2))
max_lengh = max(len(lst1), len(lst2))

for i in range(max_lengh):
    for j in range(max_lengh):
        if lst1[i % min_lengh] == lst2[j % min_lengh]:
            list.append(lst1[i])
print(list)

i is set up as the range iterator. So it has int values like 0, 1, 2.... So you can't do i[0]. That's why you get the error.

I can't make out what the modulo operator is trying to accomplish when comparing two list of lists or why you're checking i[0] but you probably meant to use i like this instead:

if lst1[i % min_lengh] == lst2[i % min_lengh]:

...which you did correctly in your append line:

list.append(i % min_lengh)


Btw, using list as a variable name is a terrible idea because it overwrites Python's built-in list() function/constructor. So you then can't create a list using it. Maybe call it indexes or result, something meaningful and not clashing with Python's standard library names.

lst1 = [[1234, 'John Paul', 'New York'], [4567, 'Jude Law', 'London'],[7891, 'Rick Ross', 'Miami']]

lst2 = [[1234, 'John Paul', 'New York'], [7891, 'Rick Ross', 'Miami']]

list = [(x) for x in lst1 for y in lst2 if x == y]

Related