0

When I loop through my json file, it doesn't show the last one

for i in range(len(data)):
    print(i)
    if data[i]["id"] == user.id and data[i]["infractionType"] == "Warning":
        print("removed")
        data.remove(data[i])

This is what it prints

ready
0
removed
1
removed
2
airttq
  • 1
  • 4
    Modifying a list while iterating over it (even using range) is not a good idea – Joshua Nixon Jun 17 '21 at 17:02
  • 1
    Does this answer your question? [Python: Removing list element while iterating over list](https://stackoverflow.com/questions/6022764/python-removing-list-element-while-iterating-over-list) – Czaporka Jun 17 '21 at 22:55

2 Answers2

0

As per the suggestion in the comments, it isn't a good idea to remove elements while iterating through a list. The easiest fix is just to remove the elements after looping.

toRemove = []
for i in range(len(data)):
print(i)
if data[i]["id"] == user.id and data[i]["infractionType"] == "Warning":
    print("removed")
    toRemove.append(i)
for i in toRemove:
    data.remove(data[i])
Kingsley Zhong
  • 358
  • 2
  • 9
0

try it:

index = 0
for i in range(len(data)):
    print(i)
    if data[index]["id"] == user.id and data[index]["infractionType"] == "Warning":
        print("removed")
        data.pop(0)
    else:
        index += 1

and check it:

>>> a = [1, 2, 1, 3, 4, 5]
>>> len(a)
6
>>> a.remove(1)
>>> a
[2, 3, 4, 5]
>>> len(a)
4
# -------------------------------
>>> a = [1, 2, 1, 3, 4, 5]
>>> len(a)
6
>>> a.pop(0)
>>> a
[2, 1, 3, 4, 5]
>>> len(a)
5