Delete Last Element

来源:互联网 发布:java springmvc 分页 编辑:程序博客网 时间:2024/06/05 08:50

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

up vote13down votefavorite
1

yo folks, I have an issue with clearing lists. In the current program which I'm coding, 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 elementfrom the lists. Is there anyway 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.

shareimprove this question
 
2 
I don't see the relation between the question title and body. – fortran Dec 2 '11 at 14:54
 
Sorry about that, that was a leftover from an old, unposted question, now fixxxed. – user1036197 Dec 2 '11 at 14:59
3 
If you don't want to clear your lists, why would you call a method called clearLists? – Wooble Dec 2 '11 at 15:07
1 
Am I the only what that do not understand what are you looking for? – Tadeck Dec 2 '11 at 15:52

2 Answers

activeoldestvotes
up vote35down vote

you can use lst.pop() or del lst[-1]

shareimprove this answer
 
 
that pop() method rocks, thanks – armani Nov 18 '14 at 22:49
 
pop() removes and returns the item, in case you don't want have a return use del ;) – flacle 2 days ago
up vote4down vote

To delete the last element of the lists, you could use:

def deleteLast(self):    if len(self.Ans) > 0:        del self.Ans[-1]    if len(self.masses) > 0:        del self.masses[-1]
0 0