Home > Blockchain >  IndexError: list index out of range with api
IndexError: list index out of range with api

Time:05-07

all_currencies = currency_api('latest', 'currencies')  # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']

while len(moedas_importantes) != 0:
    for codigo, moeda in all_currencies.items():
        if codigo == moedas_importantes[0]:
            cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
            texto  = f'{moeda} ({codigo.upper()}) = R$ {cotacao}   [{data}]\n'
            moedas_importantes.remove(codigo)
            if len(moedas_importantes) == 0: break  # WITHOUT THIS LINE, GIVES ERROR

Why am I getting this error? the list actually runs out of elements, but the code only works with the if

CodePudding user response:

You have a nested loop. The while loop is entered and then execution immediately starts in the for loop. Execution remains in the for loop for all elements in all_currencies.items(). Each time codigo is found at the beginning of moedas_importantes, that element is removed. Eventually you remove all elements from moedas_importantes, but you are still in the for loop and check if codigo == moedas_importantes[0]. At this point moedas_importantes is empty so you get an index error.

I think the below code will work without the nested loops. Note, this assumes all elements in moedas_importantes are also keys in all_currencies.

all_currencies = currency_api('latest', 'currencies')  # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']

while len(moedas_importantes) != 0:
    codigo = moedas_importantes[0]
    moeda = all_currencies[codigo]
    cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
    texto  = f'{moeda} ({codigo.upper()}) = R$ {cotacao}   [{data}]\n'
    moedas_importantes.remove(codigo)
  • Related