How delete multiple elemens from ListCtrl

Hello.
I have a code to delete multiple items from a ListCtrl, but when I run it i have a error (IndexError: pop index out of range
).
How can i repair this code? or there is another beter mode to this word?

import wx

class Program(wx.Frame):
def init(self, parent, title):
super().init(parent,title = title)
self.Center()
self.Show()
self.panel = wx.Panel(self)
self.list = wx.ListCtrl(self.panel, -1, style= wx.LC_REPORT|wx.LC_VRULES)
self.list.InsertColumn(0, ‘Animals’)
self.animals = [‘cat’, ‘duck’, ‘dog’, ‘cow’, ‘bat’, ‘mouse’]
self.button = wx.Button(self.panel, -1, ‘Del’)
self.Bind(wx.EVT_BUTTON, self.delete, self.button)
self.make_list()

def make_list(self):
	id = self.list.GetItemCount()
	for animal in self.animals:
		self.list.InsertStringItem(id, animal)
		id = id+1

def delete(self, event):
	all = self.list.GetItemCount()
	for item in range(0, all - 1):
		selected = self.list.IsSelected(item)
		if selected == True:
			self.animals.pop(item)
	self.make_list()

app =wx.App()
Program(None, ‘Title’)
app.MainLoop()

You’re iterating over the number of items, while at the same time you are removing the items from self.animals. Once you have removed one item from self.animals, your indices are out of sync.

range(0, all-1) is probably not what you want. range will return all-2 as last value.

Try code like this:

delete = [i for i in range(self.list.GetItemCount()) if self.list.IsSelected(i)]

for i in reversed(delete):
    del self.animals[i]

Get a proper IDE to run your code in a debugger. This will make your life easier.

1 Like

Thank you for your help, now I understand it.