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
213 views
in Technique[技术] by (71.8m points)

python - Add entry to beginning of list and remove the last one

I have a list of about 40 entries. And I frequently want to append an item to the start of the list (with id 0) and want to delete the last entry (with id 40) of the list.

How do I do this the best?

Example with 5 entries:

[0] = "herp"
[1] = "derp"
[2] = "blah"
[3] = "what"
[4] = "da..."

after adding "wuggah" and deleting last it should be like:

[0] = "wuggah"
[1] = "herp"
[2] = "derp"
[3] = "blah"
[4] = "what"

And I don't want to end up manually moving them one after another all of the entries to the next id.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use insert() to place an item at the beginning of the list:

myList.insert(0, "wuggah")

Use pop() to remove and return an item in the list. Pop with no arguments pops the last item in the list

myList.pop() #removes and returns "da..."

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

...