Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...