Add entry to list and delete first in Python

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

how can i make it better?

like: (example with 5 entries)

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

after adding “wuggah” and removing the latter, it should look like this:

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

or add it and delete first.

And I don't want to manually manually move all of their entries to the next identifier.

+8
python list append
source share
5 answers

Use collections.deque :

 >>> import collections >>> q = collections.deque(["herp", "derp", "blah", "what", "da.."]) >>> q.appendleft('wuggah') >>> q.pop() 'da..' >>> q deque(['wuggah', 'herp', 'derp', 'blah', 'what']) 
+7
source share

Use insert() to place an element at the top of the list:

 myList.insert(0, "wuggah") 

Use pop() to remove and return an item in a list. Pop without arguments displays the last item in the list

 myList.pop() #removes and returns "da..." 
+10
source share

Use collections.deque

 In [21]: from collections import deque In [22]: d = deque([], 3) In [24]: for c in '12345678': ....: d.appendleft(c) ....: print d ....: deque(['1'], maxlen=3) deque(['2', '1'], maxlen=3) deque(['3', '2', '1'], maxlen=3) deque(['4', '3', '2'], maxlen=3) deque(['5', '4', '3'], maxlen=3) deque(['6', '5', '4'], maxlen=3) deque(['7', '6', '5'], maxlen=3) deque(['8', '7', '6'], maxlen=3) 
+4
source share

This is single-line, but it is probably not as effective as some others ...

 myList=["wuggah"] + myList[:-1] 

Also note that it creates a new list, which may not be what you want ...

+1
source share

Another approach

 L = ["herp", "derp", "blah", "what", "da..."] L[:0]= ["wuggah"] L.pop() 
+1
source share

All Articles