Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/8358101/list-method-to-delete-last-element-in-list-as-well-as-all-elements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...