lolcats4u
lolcats4u

Reputation: 127

Looping through 2d array removing elements, indexing error, python

I am trying to delete empty elements of a list named report info split but keep getting list out of range errors.

The list looks similar to this :

reportinfosplit = [[1,,g,5,44,f][1,5,4,f,g,,g]]

I have found many answers to this for 1d arrays but not 2d. Is there a way to prevent the index from going out of range? The list elements are not all the same size, and I thought that was the reason, but it kept happening after I made them the same length.

for i in range(len(reportinfosplit)):
    for j in range(len(reportinfosplit[i])):
        if(j<=len(reportinfosplit[i])):
            if reportinfosplit[i][j] == "":
                del reportinfosplit[i][j]

Upvotes: 0

Views: 64

Answers (3)

Rakesh
Rakesh

Reputation: 82765

You can use filter to remove empty values from list

reportinfosplit = [[1,"","g",5,44,"f"],[1,5,4,"f","g","","g"]]
print([filter(None, i) for i in reportinfosplit])     #Python3 print([list(filter(None, i)) for i in reportinfosplit])

Output:

[[1, 'g', 5, 44, 'f'], [1, 5, 4, 'f', 'g', 'g']]

Upvotes: 2

FlyingTeller
FlyingTeller

Reputation: 20482

You are checking j for j<=len(reportinfosplit[i]), which results in j being able to become as large as the current length of reportinfosplit[i] (which is possible, since the current length of reportinfosplit[i] changes). Try it like this:

for i in range(len(reportinfosplit)):
    for j in range(len(reportinfosplit[i])):
        if(j<len(reportinfosplit[i])):
            if reportinfosplit[i][j] == "":
                del reportinfosplit[i][j]

Upvotes: 0

JahKnows
JahKnows

Reputation: 2706

Using list comprehensions

reportinfosplit = [[1,"",'g',5,44,'f'],[1,5,4,'f','g',"",'g']]

for ix, i in enumerate(reportinfosplit):
    reportinfosplit[ix] = [val for val in i if val != '']

print(reportinfosplit)

[[1, 'g', 5, 44, 'f'], [1, 5, 4, 'f', 'g', 'g']]

Upvotes: 0

Related Questions