Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List method to delete last element in list as well as all elements

I have an issue with clearing lists. In the current program, I have a method that clears a certain number of lists. 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.

like image 744
user1036197 Avatar asked Dec 02 '11 14:12

user1036197


People also ask

Which method is used to remove last element of element in 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.

How do you delete the last item in a list Python?

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.

How do you remove the last two elements of a list in Python?

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.

Which method is used to delete all the elements from list?

clear() :- This function is used to erase all the elements of list.


2 Answers

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

like image 180
fortran Avatar answered Oct 14 '22 23:10

fortran


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]  
like image 42
Vishnu Kiran Avatar answered Oct 14 '22 23:10

Vishnu Kiran