tivoo
tivoo

Reputation: 125

Iterate through list to create new list with IDs Python

So I am trying to use the IMDBpy module to connect a list of programs to their respective Genres. First I am trying to get a new list of their IMDB IDs to, from there, get their corresponding Genre. Unfortunately I am unable to iterate through my list of programs and generate a new list of corresponding IDs. Somehow my function gets stuck at the first iteration. What am I missing in my definition?

from imdb import IMDB
ia = IMDb()
programs = ['midsomer murders', 'wheeler dealers: dream car', 'solo: a star wars story (2018)']
def ids_list(x):
    ids = []
    for item in list(x):
        movie = ia.search_movie(item)[0].getID()
        for movie in movies:
            ids.append(movie)
        return ids
    
ids_list(programs)

output:

['0118401']

As you can see only the first item comes through, whereas my code suggests it should append every item in the list after running it through ia.search_movie(item)[0].getID(). Thanks in advance!

Upvotes: 1

Views: 204

Answers (2)

user120242
user120242

Reputation: 15268

Your return is indented incorrectly. It returns after the first iteration of the for loop:

from imdb import IMDb
ia = IMDb()
programs = ['midsomer murders', 'wheeler dealers: dream car', 'solo: a star wars story (2018)']
def ids_list(x):
    ids = []
    for item in list(x):
        movie = ia.search_movie(item)
        if movie:
          ids.append(movie[0].getID())
        else:
          ids.append(None)
    return ids
    
print(ids_list(programs))

shortened version using list comprehension and assignment operator (Python 3.8+):

from imdb import IMDb
ia = IMDb()
programs = ['midsomer murders', 'wheeler dealers: dream car', 'solo: a star wars story (2018)']
def ids_list(x):
    return [m[0].getID() if (m:=ia.search_movie(i)) else None for i in x]
    
print(ids_list(programs))

Upvotes: 1

Sowjanya R Bhat
Sowjanya R Bhat

Reputation: 1168

I mean change your for-loop code to this :

for item in list(x):
    if len(ia.search_movie(item)):
        movies = ia.search_movie(item)[0].getID()
        [ids.append(movie) for movie in movies]
return ids

Upvotes: 1

Related Questions