1

My requirement is to delete the row having any element with text "Podcast" . audio is list of lists of xml elements

 for i in range(len(audio)):
        for j in range(len(audio[i])):
            if audio[i][j].text=="Podcast":
                del audio[i]

I'm getting error: IndexError: list index out of range But I'm able to print the same thing that I'm trying to delete.

for i in range(len(audio)):
    for j in range(len(audio[i])):
        if audio[i][j].text=="Podcast":
            print(audio[i])

Result :

[<Element 'key' at 0x043253C0>, <Element 'integer' at 0x043253F0>, <Element 'key' at 0x04325420>, <Element 'string' at 0
x04325450>, <Element 'key' at 0x04325480>, <Element 'string' at 0x043254B0>, <Element 'key' at 0x043254E0>, <Element 'st
ring' at 0x04325510>, <Element 'key' at 0x04325540>, <Element 'string' at 0x04325570>, <Element 'key' at 0x043255A0>, <E
lement 'string' at 0x043255D0>, <Element 'key' at 0x04325600>, <Element 'integer' at 0x04325630>, <Element 'key' at 0x04
325660>, <Element 'integer' at 0x04325690>, <Element 'key' at 0x043256C0>, <Element 'integer' at 0x043256F0>, <Element '
key' at 0x04325720>, <Element 'date' at 0x04325750>, <Element 'key' at 0x043257B0>, <Element 'date' at 0x043257E0>, <Ele
ment 'key' at 0x04325840>, <Element 'integer' at 0x04325870>, <Element 'key' at 0x043258A0>, <Element 'integer' at 0x043
258D0>, <Element 'key' at 0x04325900>, <Element 'integer' at 0x04325930>, <Element 'key' at 0x04325960>, <Element 'integ
er' at 0x04325990>, <Element 'key' at 0x043259C0>, <Element 'date' at 0x043259F0>, <Element 'key' at 0x04325A50>, <Eleme
nt 'date' at 0x04325A80>, <Element 'key' at 0x04325AE0>, <Element 'integer' at 0x04325B10>, <Element 'key' at 0x04325B40
>, <Element 'string' at 0x04325B70>, <Element 'key' at 0x04325BD0>, <Element 'string' at 0x04325C00>, <Element 'key' at
0x04325C30>, <Element 'true' at 0x04325C60>, <Element 'key' at 0x04325C90>, <Element 'true' at 0x04325CC0>, <Element 'ke
y' at 0x04325CF0>, <Element 'string' at 0x04325D20>, <Element 'key' at 0x04325D50>, <Element 'integer' at 0x04325DB0>, <
Element 'key' at 0x04325DE0>, <Element 'integer' at 0x04325E40>]
Leo
  • 868
  • 1
  • 13
  • 32

2 Answers2

4
result = [row for row in audio if not "Podcast" in row]

It means that all rows with "Podcast" in it will be removed.

1

If you change the list while iterating over it it will have side effects like indexing errors.

You should instead use a list comprehension with the right condition.

Your condition is that none of the elements in a row has "Podcast" as an item. So your code could be something like

audio = [row for row in audio if not any(item.text == "Podcast" for item in row)]
Klaus D.
  • 13,874
  • 5
  • 41
  • 48