Python Forum
IndexError: list index out of range
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IndexError: list index out of range
#1
Hello guys...

What's going on with my code?
from tempfile import NamedTemporaryFile
from FlightRadar24.api import FlightRadar24API
from time import time, sleep
from datetime import datetime
import shutil
import csv
from pandas import DataFrame
import re
import threading
import schedule 
import time 
import sched, time

nav = []
n_acft_voando = []
while True:    

    fr_api = FlightRadar24API()
    empresas = ['AZU', 'GLO', 'LAN']
    #, 'JBU', 'AAL', 'DAL', 'ACA', 'UAL'
    pattern = "<(.*?)>"

    agora = datetime.now()
    dia = agora.strftime("%d/%m/%Y")
    hora = agora.strftime("%H:%M:%S")

    for i in range(0,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
        dados_voo = fr_api.get_flights(airline = empresas[i])

        for k in range (0,len(dados_voo)):
            substring = re.search(pattern, str(dados_voo[k])).group(1)
            substring = substring.split(' - ')
            modelo_tail = [x.replace(" ", ";") for x in substring]
            n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
            acft_voando=[dia, hora, modelo_tail[0]]
            print(acft_voando)

            with open(r'C:\Users\bruno\Desktop\Voos\DB\AeronavesAr.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(n_acft_voando)

            with open(r'C:\Users\bruno\Desktop\Voos\DB\DetalhesAeronaves.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(acft_voando)

    sleep(60)
I'm getting the following error:
Error:
IndexError Traceback (most recent call last) <ipython-input-2-aac74b35f2b2> in <module> 33 substring = substring.split(' - ') 34 modelo_tail = [x.replace(" ", ";") for x in substring] ---> 35 n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]] 36 acft_voando=[dia, hora, modelo_tail[0]] 37 print(acft_voando) IndexError: list index out of range
How can I fix it?
It's interesting because, smetimes it works, and sometimes it doesn't.
Reply
#2
list index out of range means you've used an index that is beyond the end of the list.

In your case you refer to nav[2] in that expression. If nav does not have three elements in it when that expression is evaluated, you'll get that error.

nav starts off empty and you only add one element to it when you reach line 28, so this should fail every time, unless dados_voo is empty. If that's empty, then you don't enter the loop and have a chance to make nav longer.
Reply
#3
(Mar-25-2021, 04:51 AM)bowlofred Wrote: list index out of range means you've used an index that is beyond the end of the list.

In your case you refer to nav[2] in that expression. If nav does not have three elements in it when that expression is evaluated, you'll get that error.

nav starts off empty and you only add one element to it when you reach line 28, so this should fail every time, unless dados_voo is empty. If that's empty, then you don't enter the loop and have a chance to make nav longer.

Thank you...
But, how could you fix it?
I have no idea
Reply
#4
Don't call this:
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
Until you've done this three times:
    for i in range(0,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
It is difficult to say how such a thing is accomplished since it depends as much on what the program does as the nuts and bolts of coding the program so it doesn't crash. Right now all I have to work with is some code that doesn't work. it is difficult to know how to fix it unless I know what it is SUPPOSED to do.

What does this line do?
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
[/python]
Why does in need nav[0], nave[1] and nav[2]? What are nav[0], nav[1] and nav[2]?
I find it suspicious that these indices are hard coded when the outer loop may run more than 3 times based on this:
    empresas = ['AZU', 'GLO', 'LAN']
    #, 'JBU', 'AAL', 'DAL', 'ACA', 'UAL'
Is this a hint that empresas may be a larger list?. If so, maybe the proper way to code this is:
    for i in range(2):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))

    for i in range(2,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
        dados_voo = fr_api.get_flights(airline = empresas[i])
 
        for k in range (0,len(dados_voo)):
            substring = re.search(pattern, str(dados_voo[k])).group(1)
            substring = substring.split(' - ')
            modelo_tail = [x.replace(" ", ";") for x in substring]
            n_acft_voando = [dia, hora, nav[i-2], nav[i-1], nav[i]]
            acft_voando=[dia, hora, modelo_tail[0]]
            print(acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\AeronavesAr.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(n_acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\DetalhesAeronaves.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(acft_voando)
Again, I don't know if this is correct.
brunolelli likes this post
Reply
#5
(Mar-25-2021, 01:42 PM)deanhystad Wrote: Don't call this:
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
Until you've done this three times:
    for i in range(0,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
It is difficult to say how such a thing is accomplished since it depends as much on what the program does as the nuts and bolts of coding the program so it doesn't crash. Right now all I have to work with is some code that doesn't work. it is difficult to know how to fix it unless I know what it is SUPPOSED to do.

What does this line do?
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
[/python]
Why does in need nav[0], nave[1] and nav[2]? What are nav[0], nav[1] and nav[2]?
I find it suspicious that these indices are hard coded when the outer loop may run more than 3 times based on this:
    empresas = ['AZU', 'GLO', 'LAN']
    #, 'JBU', 'AAL', 'DAL', 'ACA', 'UAL'
Is this a hint that empresas may be a larger list?. If so, maybe the proper way to code this is:
    for i in range(2):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))

    for i in range(2,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
        dados_voo = fr_api.get_flights(airline = empresas[i])
 
        for k in range (0,len(dados_voo)):
            substring = re.search(pattern, str(dados_voo[k])).group(1)
            substring = substring.split(' - ')
            modelo_tail = [x.replace(" ", ";") for x in substring]
            n_acft_voando = [dia, hora, nav[i-2], nav[i-1], nav[i]]
            acft_voando=[dia, hora, modelo_tail[0]]
            print(acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\AeronavesAr.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(n_acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\DetalhesAeronaves.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(acft_voando)
Again, I don't know if this is correct.

Thank you so much!
I really appreciate your help

It's working better now...

Let me ask you another question:
Why am I getting the following output:
25/03/2021;10:00:40;"(B763);CC-CXK"
25/03/2021;10:00:40;"(B789);CC-BGN"
I want to get values without those quotes, like:
25/03/2021;10:00:40;(B763);CC-CXK
25/03/2021;10:00:40;(B789);CC-BGN
How can I get rid of these double quotes?
Reply
#6
(Mar-25-2021, 02:04 PM)brunolelli Wrote: Why am I getting the following output:
Because you have a string that has inside the delimiter used in the file - ;. So, if it is not quoted (B763) will be one column and CC-CXK will be next column.

You can always set quoting to csv.QUOTE_NONE, but that's obviously not advisable.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
(Mar-25-2021, 02:13 PM)buran Wrote:
(Mar-25-2021, 02:04 PM)brunolelli Wrote: Why am I getting the following output:
Because you have a string that has inside the delimiter used in the file - ;. So, if it is not quoted (B763) will be one column and CC-CXK will be next column.

You can always set quoting to csv.QUOTE_NONE, but that's obviously not advisable.

The fact is that I don't want this information as it's written... I really need it separated, (B738) in one collumn and PR-YSA in another column. How can I do that?
Reply
#8
writer = csv.writer(f, delimiter=';', quoting = csv.QUOTE_NONE)
Note - I didn't look at previous discussion - maybe it's a problem that it was not split when the rest was split? I see the code is quite confusing and unclear and we don't have the source data.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
(Mar-25-2021, 02:26 PM)buran Wrote:
writer = csv.writer(f, delimiter=';', quoting = csv.QUOTE_NONE)
Note - I didn't look at previous discussion - maybe it's a problem that it was not split when the rest was split? I see the code is quite confusing and unclear and we don't have the source data.

Yep, I totally agree with you..
This is my first time programming and I have no previus experience with Python...
Reply
#10
I'll try to explain my problem and how I'm trying to solve it with this code:

Basically, running this code I'm able to collect some info of aircrafts flying right now from an airline called AZU
from FlightRadar24.api import FlightRadar24API
fr_api = FlightRadar24API()

fr_api.get_flights(airline = 'AZU')
And the output looks like this:
[<(A332) PR-AIW - Altitude: 25300 - Ground Speed: 429 - Heading: 328>,
 <(A20N) PR-YSC - Altitude: 27850 - Ground Speed: 436 - Heading: 216>,
 <(A20N) PR-YRV - Altitude: 12900 - Ground Speed: 370 - Heading: 251>,
 <(C208) PR-WOT - Altitude: 1900 - Ground Speed: 164 - Heading: 84>,
 <(E295) PS-AEH - Altitude: 28725 - Ground Speed: 432 - Heading: 44>,
 <(A20N) PR-YSF - Altitude: 6725 - Ground Speed: 282 - Heading: 32>,
 <(A20N) PR-YSG - Altitude: 20575 - Ground Speed: 424 - Heading: 209>,
 <(E195) PR-AXY - Altitude: 27000 - Ground Speed: 453 - Heading: 72>,
 <(E195) PR-AXB - Altitude: 17650 - Ground Speed: 345 - Heading: 210>]
But I would like to run this code for more than one airline, like 'AZU', 'GLO', 'AAL', 'UAL', and so on...
And export this data to a TXT file, adding more two columns ([Date][Time]).

Moreover, I would like to run this code every minute, and keep upadating my TXT file.
How can I do that?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  IndexError: index 10 is out of bounds for axis 0 with size 10 Mehboob 11 1,951 Sep-14-2023, 06:54 AM
Last Post: Mehboob
Thumbs Down I hate "List index out of range" Melen 20 3,161 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 5,967 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,844 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,280 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,409 May-03-2022, 01:39 PM
Last Post: Anldra12
  TypeError: list indices must be integers or slices, not range Anldra12 2 2,501 Apr-22-2022, 10:56 AM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,104 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,761 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,239 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020