Home > database >  Returns an error (IndexError: list index out of range on line 18) when trying to select the second e
Returns an error (IndexError: list index out of range on line 18) when trying to select the second e

Time:09-18

import csv

list = []

with open('games.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)

    for row in reader:
        cond = int(row['white_rating']) - int(row['black_rating'])

        if -100 <= cond <= 100 and row['winner'] == 'white':
            move = str(row['moves'])
            move = move.split()[0]
            list.append(move)

        elif -100 <= cond <= 100 and row['winner'] == 'black':
            move = str(row['moves'])
            move = move.split()[1]
            list.append(move)


print(len(list))

Error

Traceback (most recent call last): 
  File "C:\Users\Said\Desktop\Шахматы\main.py", line 18, in <module> 
    move = move.split()[1] 
IndexError: list index out of range

CVS file: https://docs.google.com/spreadsheets/d/1HkVhU_DL22OquSbvuhKUhbWHMVNE2Qek9Q88mKGKs_4/edit#gid=230018563

CodePudding user response:

There is one of the moves that just have one movement, that is the reason, it fails in ['d3'] element, so add a condition to resolve that case

elif -100 <= cond <= 100 and row['winner'] == 'black':
    move = str(row['moves'])
    move = move.split()[1] # <- fails here because move = 'd3'
    list.append(move)
  • Related