Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting "IndexError: list index out of range" and not sure why

Beginner python programmer here. I understand what an "IndexError: list index out of range" error means, but in my case I’m not sure why I’m getting it. I have a script which goes to this webpage (https://www.basketball-reference.com/players/v/valanjo01/gamelog/2022) and in the "2021-22 Regular Season" table, goes through all of the rows and prints out the values in the "Rk" column.

This is my code:

team_game_number_element = []
team_game_number = []

for x in range(82):
    y = str(x + 1)
    team_game_number_element[x].append(driver.find_element_by_xpath('//th[@data-stat="ranker" and contains(., "' + y + '")]'))
    team_game_number[x].append(team_game_number_element[x].text)
    print(team_game_number[x])

What I was expecting:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x starts at 0, y becomes "1". Then team_game_number_element[0] is assigned to the element with that xpath (specifically the one which contains the value of y). Then team_game_number[0] is assigned the value of the text of team_game_number_element[0].

>Solution :

The append() method appends/add an element to the end of the list.

In your code you can remove the index before the append method.

team_game_number_element = []
team_game_number = []

for index in range(82):
    y = str(index + 1)
    team_game_number_element.append('some text')
    team_game_number.append(team_game_number_element[index])
    print(index, team_game_number[index], y)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading