0

I'm trying to code a program that opens a file, creates a list that contains each line of this file, and removes some words from this list. I have an Index Out of Range error.

#! /usr/bin/python3

# open the file
f = open("test.txt", "r")
# a list that contains each line of my file (without \n)
lines = f.read().splitlines()
# close the file
f.close()

# some words I want to delete from the file
data = ["fire", "water"]

# for each line of the file...
for i in range(len(lines)):
    # if this line is in [data]
    if lines[i] in data:
        # delete this line from [data]
        print(lines[i])
        del lines[i]

This is my text file:

sun
moon
*
fire
water
*
metal

This is my output:

fire
Traceback (most recent call last):
  File "debug.py", line 16, in <module>
    if lines[i] in data:
IndexError: list index out of range
Mike Delta
  • 726
  • 2
  • 16
  • 32

1 Answers1

0

I'll address the out of index error first. What's happening, in your first post, is that it takes the length of the list which is 7, so len(lines) = 7 which will result in range(7) = (0,7) which will do this:

  • lines[0] = sun
  • lines[1] = moon
  • lines[2] = *
  • lines[3] = fire
  • lines[4] = water
  • lines[5] = *
  • lines[6] = metal

=>

  • lines[0] = sun
  • lines[1] = moon
  • lines[2] = *
  • deleted lines[3] = fire
  • lines[3] = water
  • lines[4] = *
  • lines[5] = metal

If you now delete lines[3] it will still try to iterate over lines[6] although it won't exist anymore.

It will also continue to iterate over the next index lines[4] so water will never be checked, it is absorbed.

I hope this helps and I suggest you do this instead:

# open the file
f = open("test.txt", "r")
# a list that contains each line of my file (without \n)
lines = f.read().splitlines()
# close the file
f.close()

# some words I want to delete from the file
data = ["fire", "water"]


for i in data:
    if i in lines:
        lines.remove(i)

print(lines)

Output: ['sun', 'moon', '', '', 'metal']

Wonnebju
  • 1
  • 1
  • Don't forget to adjust the solution for multiple occurances! – Wonnebju Jan 15 '18 at 18:40
  • In summary: Don't delete list elements, while iterating over the list. And what @Wonneju said: You only delete the first occurence of each `data` item in `lines`. – Mr. T Jan 15 '18 at 19:07