AJP AJP - 1 year ago 46
Python Question

List comprehension - Iterating over nested lists

I am trying to write a function that searches nested lists in their entirety to return all lists that contain a certain word, but this only returns


word = "what song?"
def searchSong(mp3_list, word):
search = input((word))
match = [i for i in mp3_list if search in i[2]]
for confirmed in match:
print(confirmed[0],'\n', confirmed[1],'\n', confirmed[2])

print(searchSong(mp3_list, word))

When I do comparison testing, the
variable still returns nothing:

mp3_list = [["Eric Clapton","Tears in heaven","Rush"],["Neil Young", "Heart of gold", "Harvest"]]
match = [i for i in mp3_list if 'heaven' in i[2]]
print(match) #returns []

But this works, despite the syntax appearing exactly the same:

li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"]]
match = [i for i in li if 'ar' in i[2]]
print(match) #returns [['0', '20', 'ar'], ['50', '199', 'bar']]

Any help would be much appreciated :)

Answer Source

'heaven' is present in the second element in ["Eric Clapton","Tears in heaven","Rush"], but you're checking the third element (i[2]). Python arrays are indexed starting from 0, not 1. (But you appear to know this, as your second example looks for "ar" in i[2], which is correct.)

Also, searchSong() doesn't return anything, therefore it always returns None by default.