I have an issue with clearing list
s. In the current program, I have a method that clears a certain number of list
s. This is rather inconvenient since during one part of the program where this method is used, it would be a lot more helpful if it only deleted the last element from the lists. Is there any way in which I can set index numbers as parameters to my method to solve this problem?
The code for the method
def clearLists(self): del self.Ans[:] del self.masses[:]
Whenever I want to use this method, I merely write self.ClearLists()
and it deletes every element in a list.
pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.
Using del The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1. The use of the negative index allows us to delete the last element, even without calculating the length of the list.
Method #1: Using len() + list slicing List slicing can perform this particular task in which we just slice the first len(list) – K elements to be in the list and hence remove the last K elements.
clear() :- This function is used to erase all the elements of list.
you can use lst.pop()
or del lst[-1]
pop()
removes and returns the item, in case you don't want have a return use del
To delete the last element from the list just do this.
a = [1,2,3,4,5] a = a[:-1] #Output [1,2,3,4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With