A
A
Andrey Godunko2021-11-18 22:28:36
Python
Andrey Godunko, 2021-11-18 22:28:36

How to fix IndexError: list index out of range error?

data = []
with open("num.txt") as f:
    for line in f:
        data.append([float(x) for x in line.split()])
print(data)

a = data[1]
print(a)

Please give answer with correct code and explanation
Thanks :-)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ananchenko, 2021-11-19
@Noy-name-boy

IndexError: list index out of range | Index error: List index out
of range

>>> data = ['1','2','3'] # Создан лист с тремя элементами
>>> data[0] # Выводим первый элемент
'1'
>>> data[1] # Выводим второй элемент
'2'
>>> data[2] # Выводим третий элемент
'3'
>>> data[3]# Выводим четвертый элемент, и получаем ошибку индекса
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

V
Vindicar, 2021-11-18
@Vindicar

There's nothing on your list, I presume. This will happen if the file exists but is empty.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question