I want to create a list that can only accept certain types. As such, I\'m trying to inherit from a list in Python, and overriding the append() method like so:
You can also use build-in array class. It works only with numeric types, but is probably best solution for such cases. It is optimized to minimize memory usage.
Example:
from array import array
array('c', 'hello world') # char array
array('u', u'hello \u2641') # unicode array
array('l', [1, 2, 3, 4, 5]) # long array
array('d', [1.0, 2.0, 3.14]) # double array
You can perform the same operations as with normal list:
chars = array('c')
chars.extend('foo')
But when you try to insert other type then specified, an exception is raised:
>>> chars.extend([5,10])
Traceback (most recent call last):
File "", line 1, in
TypeError: array item must be char
For all available types look here