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
  index of range, but data prints out mrc06405j 1 320 Mar-25-2021, 07:20 PM
Last Post: buran
  Changing Index of 2 List in python giddyhead 0 298 Mar-05-2021, 05:45 PM
Last Post: giddyhead
  IndexError: list index out of range ramu4651 2 519 Jan-24-2021, 01:45 PM
Last Post: buran
  string index out of range jade_kim 4 451 Jan-13-2021, 05:41 AM
Last Post: jade_kim
  IndexError: index 10 is out of bounds for axis 0 with size 1 vahid89 1 1,474 Jan-07-2021, 06:19 PM
Last Post: deanhystad
Question Matching variable to a list index Gilush 17 997 Nov-30-2020, 01:06 AM
Last Post: Larz60+
  How to get index of minimum element between 3 & 8 in list Mekala 2 710 Nov-10-2020, 12:56 PM
Last Post: DeaD_EyE
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 625 Nov-04-2020, 11:26 AM
Last Post: Aggam
  List index out of range error while accessing 2 lists in python K11 2 568 Sep-29-2020, 05:24 AM
Last Post: K11
  list vs [] with range quazirfan 5 671 Sep-19-2020, 12:45 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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