Reputation: 61
I'm getting this error: index out of range, in if largerList[j] == smallerList[i]
. I'm working on an assignment about binary search trees, I put the trees into lists and I'm just trying to compare the two lists:
def matchList(largerList, smallerList) :
matches = []
for i in smallerList:
for j in largerList:
if largerList[j] == smallerList[i] :
matches[i] = smallerList[i]
return matches
I'm assuming nested for loops should totally iterate all elements in each loop, so smallerList
is the smaller list so smallerList
doesn't make largerList
go out of bounds. The inner for-loop should iterate over all of the larger list entirely, comparing each value to each element of the smaller list. Why doesn't it work?
Upvotes: 2
Views: 790
Reputation: 4322
Trying to find matching elements in lists like this is rather inefficient. One thing you could improve to make it arguably more pythonic is to use a list comprehension:
matches = [i for i in largerList if i in smallerList]
But then the more mathematically sensible approach still would be to realise that we have two sets of elements and we want to find an intersection of two sets so we can write something like:
matches = set(largerList).intersection(smallerList)
Upvotes: 1
Reputation: 261
You can't set a list value with matches[i]
if that index does not exist in matches
.
Try appending instead:
Change this matches[i] = smallerList[i]
to this matches = matches.append(smallerList[i])
Upvotes: 1