2

I'm trying to count how many certain string (in this case 'v') exist in a list. But when I run the code, it gives me index out of range error. The list is created by line.split() method

So this is what I've got:

for line in open('cube.obj','r').readlines():
    rawdata = line.split()[0:]
    data = line.split()[1:]
    obj.add_last(data)
    if rawdata[0] == 'v':
        v_count += 1

cube.obj file is following:

# cube
v 0.0 0.0 0.0
v 1.0 0.0 0.0
v 1.0 0.0 1.0
v 0.0 0.0 1.0
v 0.0 1.0 1.0
v 0.0 1.0 0.0
v 1.0 1.0 0.0
v 1.0 1.0 1.0

f 1 2 3 4
f 6 7 8 5
f 2 3 8 7
f 1 4 5 6
f 3 4 5 8
f 1 2 7 6

Any help is appreciated Thanks!

zakels
  • 87
  • 6

2 Answers2

1

If you're getting an Index out of range error it's because you're making a reference to an entry of a list that doesn't exist.

In your case, that looks likelyto be rawdata[0] == 'v'

If rawdata is an empty list, this would cause the error. This would happen if your line is an empty string.

line = ''
rawdata=line.split()[0:]
rawdata
> []
rawdata[0]
> ---------------------------------------------------------------------------
> IndexError                                Traceback (most recent call last)
> <ipython-input-4-c81248904650> in <module>()
> ----> 1 rawdata[0]
> IndexError: list index out of range

To skip this, test to see if the line is empty and if so continue to the next line.

for line in ['', '', 'a', 'b']:
   if not line:
       continue
   rawdata = line.split()[0:]
   print rawdata[0]

> a
> b
Joel
  • 22,598
  • 6
  • 69
  • 93
  • Thanks. There was a blank line in the file. Is there any way I can get around to ignore an empty list and count 'v'? – zakels Feb 28 '15 at 00:43
  • have edited to show how to `continue` (i.e., skip the rest of the statements and go to next step in loop) – Joel Feb 28 '15 at 00:48
  • Okay thanks, I see. But does continue method work on my case? I've edited my post so I can tell you what I'm trying to do. – zakels Feb 28 '15 at 00:59
  • See this on how `continue` works http://stackoverflow.com/questions/8420705/example-use-of-continue-statement-in-python It will work in your case. – Joel Feb 28 '15 at 05:36
1

You can sum with a generator expression catching empty lines with if line.strip() to we don't get an IndexError indexing an empty list:

def  counts(f,ch):
    with open(f) as in_file:
        return sum(line.split()[0] == ch for line in in_file if line.strip())
print(counts("words.txt","v"))
8

if line.strip() will only be True when the line is not empty.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321