Skip to content
Advertisement

Finding a needle in a haystack *TypeError: list indices must be integers or slices, not str*

i tried chaning from a list to a dictionary but it did not work

sorry for this newbie question, but i really tried doing it on my own for lots of time but it does not work.

I reduced the problem to finding a arrey of strings(needle) in another arrey of strings(hay). The rest i can do on my own

needle = [] 
for x in range(2015,2017):
    needle.append(str(x))


hay = [] 
for x in range(2015,2090):
    hay.append(str(x))

print(needle)
print(hay)

for a in needle:
    for b in hay:
        if needle[b] in hay[a]:
            print("Found!")
        else:        
            print("Not found!")

Advertisement

Answer

There are different numbers involved here – you have the value/element (i.e. the thing you’re adding to the array) and the index; the element’s position within that array. When comparing your needle value with your haystack value you want to compare the values (which you’re doing); but to get those values you want to look in the array in the relevant position (which you’re not).

Instead, try something like this:

needle = [] 
for x in range(2015,2017):
    needle.append(str(x))

hay = [] 
for x in range(2015,2022):
    hay.append(str(x))

print(needle)
print(hay)

for needleIndex in range(len(needle)):
    for hayIndex in range(len(hay)):
        if needle[needleIndex] == hay[hayIndex]:
            print("Found!")
        else:        
            print("Not found!")

This change means that instead of a being '2015', '2016', '2017' instead needleIndex is 0,1,2 and needle[needleIndex] is '2015', '2016', '2017'.

Hope that helps to clarify what’s going on.

ps. For this example you don’t need the indexes; you could just have

for a in needle:
    for b in hay:
        if b == a:
            print("Found!")
        else:        
            print("Not found!")

Simpler still; you’ve shown that you’re aware of the in operator; though you’ve been comparing individual values from the 2 arrays (hence I changed it to == above)… You can use your in operator like this:

for a in needle:
    if a in hay:
        print("Found!")
    else:        
        print("Not found!")

You can also use the array_intersect function to check for all elements which exist in both arrays… More on that here: https://stackoverflow.com/a/8679430/361842

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement