Home > OS >  Indexing the first element of a list of a list and add it to new list
Indexing the first element of a list of a list and add it to new list

Time:10-01

I am working with the Spotify API and trying to add the first genre of an artist of songs in a playlist to a new list:

url = 'https://api.spotify.com/v1/artists'
params = {"ids": artist_id_new} 
response_artists = requests.get(url, headers = headers , params = params).json()

genre = []

for artist in response_artists['artists']:
    genre.append(artist['genres'])

genre

the genre list output looks like this:

[['deep disco house',
  'deep house',
  'disco house',
  'float house',
  'funky house',
  'house',
  'indie soul',
  'minimal tech house'],
 ['latin', 'latin pop', 'pop venezolano', 'reggaeton', 'trap latino'],
 ['doomcore'],
 ['vapor twitch'], ...]

But the genre list should contain only the first genre and not all of them. So I was thinking of simply indexing the first element of the each iterated list item, like in the following:

for artist in response_artists['artists']:
    genre.append(artist['genres'][0])

But this always gets me an 'list index out of range' error. How can I solve this?

Thanks in advance!

CodePudding user response:

Sometimes Spotify has no genre tagged for specific artists, so you need to add a check for that in your loop:

for artist in response_artists['artists']:
    if len(artist['genres'])>0:
        genre.append(artist['genres'][0])
    else:
        genre.append(None)

This will add a None value when no genres are available.

  • Related