user1301036
user1301036

Reputation:

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.

Upvotes: 17

Views: 16494

Answers (5)

Another approach

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

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

Upvotes: 1

Marcin
Marcin

Reputation: 49826

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)

Upvotes: 13

mgilson
mgilson

Reputation: 309919

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

Upvotes: 2

Joel Cornett
Joel Cornett

Reputation: 24788

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

Upvotes: 13

phihag
phihag

Reputation: 287835

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

Upvotes: 14

Related Questions