1

After creating an axes object (names ax) and fill it with Line2D instances, I want to remove a subset from axes.lines (containing these Line2D instances), based on label.

However, when I iterate on this list and remove members, it shrinks while being evaluated and then I get a wrong count (as a matter of fact, half of it) so I can't iterate through all its members

from matplotlib import pyplot as plt
fig = plt.figure()

# creating axes object
ax = fig.add_subplot(111)

# adding plots (Line2D objects) to ax
N=30
for indx in range(N):
    ax.plot(1,1,label="my_line")

# adding another plot so the list is not identical
ax.plot(1,1,label="not_my_line")
print("I've created", len(ax.lines), "lines")

# iterating on the whole ax.lines list
for i,line in enumerate(ax.lines):
    if line.get_label() == "my_line":
        ax.lines.remove(line)

print ("I've expected to delete",N,"of them, but only",i+1 ,"lines were iterated")
print ("The remaining list is still", len(ax.lines), "lines long")
Lior
  • 11
  • 2

1 Answers1

1

You should never manipulate the list you are iterating over in python. Also see

Here an easy solution is to iterate over a (complete) slice of the original list:

for i,line in enumerate(ax.lines[:]):
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 1
    Related: [Why can’t you modify lists through "for in" loops in Python?](https://www.quora.com/Why-can%E2%80%99t-you-modify-lists-through-for-in-loops-in-Python). – Gabriel Jablonski Jul 17 '18 at 13:07