Adding item in front of a list

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Apr 9 09:22:51 EDT 2003


Thomas Guettler <pan-newsreader at thomas-guettler.de> wrote in 
news:pan.2003.04.09.14.42.36.965880.811 at thomas-guettler.de:

> I think it would be nice if
>  l=[2, 3, 4]
>  l.insert(1)
> 
> would insert in front of the list, as opposed to append() which adds new
> elements at the end.
> 
> l.insert(1) looks better than l.insert(-1,1)
> 

If you want to do this a lot you can always subclass list:

>>> class fifo(list):
	def push(self, obj):
		self.insert(0, obj)

		
>>> f = fifo()
>>> f.push(1)
>>> f.push(2)
>>> f.push(3)
>>> f
[3, 2, 1]
>>> f.pop()
1
>>> f.pop()
2
>>> f.pop()
3


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list