Delete Items From 3 Different Lists
I need some help with deleting some items from some lists at the same time, when a button is clicked. This is the code: class Window(QMainWindow): list_1 = [] #The items are st
Solution 1:
Python lists have a "remove" object that perform that action directly:
Window.list_2.remove(item_selected)
(with no need for your for loop)
If you ever need to perform more complex operations on the list items, you can retrieve an item's index with the index
method instead:
position = Window.list_2.index(item_selected)
Window.list_2[position] += "(selected)"
And in some ocasions you will want to do a for loop getting to the actual index, as well as the content at that index of a list or other sequence. In that case, use the builtin enumerate
.
Using the enumerate pattern, (if remove
did not exist) would look like:
forindex, content in enumerate(Window.list_2):
if content == item_selected:
del Window.list_2[index]
# must break out of the for loop,# as the original list now has changed: break
Solution 2:
if you have the value, then just find its index in each list and then delete it. Something like:
item_selected = self.listWidget.currentItem().text()
i = Window.list_2.index(item_selected)
if i >= 0:
del Window.list_2[i]
You can also use directly Widow.list_x.remove(value)
but it can throw an exception if the value does not exist.
Post a Comment for "Delete Items From 3 Different Lists"