Welcome, guest | Sign In | My Account | Store | Cart

In some applications, it's advantageous to be able to define a fixed length list.

The class provides all features as python internal type: list

The main focus of fixed length list is only keep certain number of items. "overflow" items will be discarded.

Python, 51 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class FixedlenList(list):
	'''
subclass from list, providing all features list has
the list size is fixed. overflow items will be discarded
	
	'''
	def __init__(self,l=0):
		super(FixedlenList,self).__init__()
		self.__length__=l #fixed length
		
	def pop(self,index=-1):
		super(FixedlenList, self).pop(index)
	
	def remove(self,item):
		self.__delitem__(item)
		
	def __delitem__(self,item):
		super(FixedlenList, self).__delitem__(item)
		#self.__length__-=1	
		
	def append(self,item):
		if len(self) >= self.__length__:
			super(FixedlenList, self).pop(0)
		super(FixedlenList, self).append(item)		
	
	def extend(self,aList):
		super(FixedlenList, self).extend(aList)
		self.__delslice__(0,len(self)-self.__length__)

	def insert(self):
		pass

##################
# test cases
##################

def test1():	
	l=FixedlenList(5)
	l.append(1)
	l.append(2)
	l.append(3)
	l.append(4)
	l.append(5)
	l.append(6)
	print repr(l)=='[2, 3, 4, 5, 6]'
	
	
def test2():
	l=FixedlenList(2)
	l.extend([11,12,13])
	print repr(l)=='[12, 13]'
Created by Hiro on Fri, 24 Jan 2014 (GPL)
Python recipes (4591)
Hiro's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks

  • Licensed under the GPL 2
  • Viewed 10161 times
  • Revision 2 (updated 10 years ago)