サーバレス練習帳

着眼大局着手小局

【PYTHONのエラー回避方法】IndexError: list index out of range

リスト(配列)に対して存在しないインデックを指定した際に発生する例外です。
“IndexError: list index out of range”

 

それが、なんと、こんな方法で回避できるとは、、、!

 

result = []
with open('hoge.txt', 'r') as f:
    for line in f:
        tmp = line.rstrip().split(',')
        result.append({
            'name': tmp[0],
            'blood_type': tmp[1] if len(tmp) > 1 else '',
            'age': tmp[2] if len(tmp) > 2 else ''
        })

print result

 

 

IndexError: list index out of range – せつないぶろぐ

 

Windows10では動いていたPython3プログラムが、Raspberry Piに移植したら発生したエラーなのですが、なんでなのかなぁ。まぁ、回避できたから良いけど。