Reputation: 13
I have a little problem - I need to iterate through a list of lists (lines in a file) and count how many times the lines begin with six or seven. It was no problem, but I also need to remove the items which repeat themselves, e.g. if I have this: [6,6,7,7,6], I need to do this out of it: [6,7,6] - it is the number of switches that counts. But somehow the list index is always out of range. Why? Thank you!
def number_of_switches(list):
counter = []
for element in li:
if int(element[0]) == 6 or int(element[0]) == 7: counter.append(element[0])
else: pass
i = 0
for i in (0, len(counter)):
if counter[i] == counter[i+1]: counter.remove(counter[i+1])
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'
Upvotes: 0
Views: 2292
Reputation: 3066
You should be doing for i in range(len(counter)):
and also if counter[i] == counter[i+1]:
will give an error in this range. You need to handle the end case.
This might be a better solution:
def number_of_switches(list):
counter = []
prev = li[0]
for element in range(1, len(li)):
if int(li[element][0]) != prev:
count.append(int(li[element][0]))
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'
Upvotes: 0
Reputation: 599610
for i in (0, len(counter))
only iterates over two elements: 0, and the length of counter
. It does not count up from 0 to the length. For that you need range:
for i in range(len(counter))
However, you should not do that either. Think about what happens each time you remove an element: the list is now one shorter, but you are iterating until the end of the original list. So you will quickly get an IndexError. You need to append the non-matching elements to a new list, rather than removing from the current one.
Upvotes: 2
Reputation: 10961
When you write:
for i in (0, len(counter)):
That means for in those two values: 0 and len(counter) and, len(counter) is the index out of range. I think you meant:
for i in range(0, len(counter)):
Upvotes: 0