Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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'])

Solution 3:

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)

Solution 4:

Here's a one-liner, but it probably isn't as efficient as some of the others ...

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

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

Solution 5:

Another approach

L = ["herp", "derp", "blah", "what", "da..."]

L[:0]= ["wuggah"]
L.pop()             

Post a Comment for "Add Entry To Beginning Of List And Remove The Last One"