Luka
Luka

Reputation: 25

What is the correct loop range

I want to delete some array from list. But I'm using wrong range. At start the range is correct. This should work, if string in variable result[b][2:3] then delete result[b]

for b in range(len(result)):
    if 'FillLevel' in result[b][2:3]:
        del result[b]

After that I have error: IndexError: list index out of range


I want to find this string and delete whole line (array):

V;4;FillLevel[1];CPUA.DB1610.0,I0,64;RW
V;4;FillLevel[2];CPUA.DB1610.0,I;RW
V;4;FillLevel[5];CPUA.DB1610.6,I;RW
V;4;FillLevel[6];CPUA.DB1610.8,I;RW
V;4;FillLevel[11];CPUA.DB1610.18,I;RW

Why this code:

print(result[4][2:3])
print(result[5][2:3])
print(result[6][2:3])
print(result[7][2:3])
print(result[8][2:3])
print(result[9][2:3])
print(result[10][2:3])

b = 0
while b < len(result):
    if 'FillLevel' in result[b][2:3]:
        del result[b]
        del adress[b]
        print('yes')
    b += 1

Showing only once 'yes' ?

['FillLevel']
['FillLevel[1]']
['FillLevel[2]']
['FillLevel[3]']
['FillLevel[4]']
['FillLevel[5]']
['FillLevel[6]']
yes

Upvotes: 0

Views: 78

Answers (4)

Matroskin
Matroskin

Reputation: 459

for first - it's mach easyer to iterate by list withot getting length, probably you are got an error coz length of list is changing during loop for second - you are trying to check 'FillLevel' in slice of string. slice return one character - try to not midify your list but make new one with filtered items like this:

new_list = []
for b in result:
    if 'FillLevel' not in b:
        new_list.append(b)

or check about List Comprehensions and type this:

[i for i in result if 'FillLevel' not in i]

Upvotes: 0

nino_701
nino_701

Reputation: 692

If you want to preserve the same list and parse it in the strait order you can use a while loop which evaluate the len(result) in each iteration

b = 0
while b < len(result) :
    if 'FillLevel' in result[b][2:3]:
        del result[b]
    b += 1 

Upvotes: 0

jakevdp
jakevdp

Reputation: 86310

Let's say there are 10 items in the list.

Half-way through you delete one of the items; now there are 9 items in the list.

In the last cycle, your loop asks for the tenth item. My guess is that's where the index error is happening (though it could be due to the [2:3] call as well, depending on the contents of your list)

A more pythonic solution would be

result = [val for val in result if 'FillLevel' not in val[2:3]]

Upvotes: 1

NPE
NPE

Reputation: 500167

The issue is that del result[b] changes the composition (and the length of) result, thereby interfering with your loop.

Perhaps the easiest way to fix this is by rephrasing your code as a list comprehension:

result = [r for r in result if 'FillLevel' not in r[2:3]]

Alternatively, you could fix it by iterating in reverse:

for b in range(len(result) - 1, -1, -1):
    if 'FillLevel' in result[b][2:3]:
        del result[b]

Upvotes: 1

Related Questions