Home > Back-end >  How to use For In loop on a list within a list
How to use For In loop on a list within a list

Time:07-04

So, I need to use a for i in loop on a list that is within a list. Let me give you an example.
I have a blacklist (list) that contains 10 categories (also lists), in those categories, there are always 2 ints.
I also have a list called x. x contains 2 ints.
I want to check if the 2 ints inside x are the same as any of the blacklist categories.
In order to do that I need to do

def blacklist_check(blacklist, z):
    for i in blacklist:
        for y in blacklist[i]:
            difference = blacklist[i][y] - z
            if difference < 10 and difference > -10:
                print(f"{difference} found")
                return False
            print(f"{difference} not found")
            if i == 10:
                return True

but when I try that I get

TypeError: list indices must be integers or slices, not list

I can not transfer the categories to ints or any other type than lists. How do I make this work?

CodePudding user response:

Here (y) is a list, you cannot nest a list as a index inside another list. Try this

def blacklist_check(blacklist, z):
    for i in blacklist:
        for y in range(len(i)):
            difference = i[y] - z
            if difference < 10 and difference > -10:
                print(f"{difference} found")
                return False
            print(f"{difference} not found")
            if i == 10:
                return True

CodePudding user response:

Python handles for loops differently to perhaps a more conventional C-Type language in that it runs based on enumeration rather than incrementation.

In your case, what you have with for i in blacklist, for each iteration of the for loop, i is set to the element rather than the index, so if your data structure looks something like:

[ [1,2,3,4], [5,6,7,8] ]

Then the first value of i will be [1, 2, 3, 4], and is hence a list. If you want the indexes rather than the elements, you could use the range and len functions in the following way:

for i in range(len(blacklist)):

which will make i be 0 on the first iteration, and 1 on the second one, etc.

That would mean that calling blacklist[i] will return [1, 2, 3, 4]

  • Related