16

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 2
    "And I don't want to end up manually moving them one after another all of the entries to the next id." Internally, a list object allocates a larger list than the size of the list that is currently used (10 elements, but list is actually a lot bigger than that). So behind the scene it is doing all that for you - this amortized the running time of insertion, pop at a particular position and other operates as low as possible. http://wiki.python.org/moin/TimeComplexity – CppLearner Apr 14 '12 at 17:37

5 Answers5

13

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'])
phihag
  • 278,196
  • 72
  • 453
  • 469
13

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..."
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
11

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)
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
Marcin
  • 48,559
  • 18
  • 128
  • 201
  • 3
    Using the max length is a better solution here, more elegant, that said, the OP wanted to prepend the item, not append it - you want ``deque.appendleft()``. Edited. – Gareth Latty Apr 14 '12 at 17:34
2

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
1

Another approach

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

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