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

Question:

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:

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].

Asked By: maxpower8888

||

Answers:

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)

Answered By: Daniel Figueroa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.