List Behavior when inserting new items

wittempj@hotmail.com martin.witte at gmail.com
Mon Jan 29 14:38:56 EST 2007


On Jan 29, 7:57 pm, "Drew" <olso... at gmail.com> wrote:
> I'm looking to add an element to list of items, however I'd like to
> add it at a specific index greater than the current size:
>
> list = [1,2,3]
> list.insert(10,4)
>
> What I'd like to see is something like:
>
> [1,2,3,,,,,,4]
>
> However I see:
>
> [1,2,3,4]
>
> Is there any way to produce this kind of behavior easily?
>
> Thanks,
> Drew

You could write your own class mimicing a list with your desired 
behaviour, something like:

py>class llist(object):
py>    def __init__(self, arg = []):
py>        self.__list = arg
py>    def __setitem__(self, key, value):
py>        length = len(self.__list)
py>        if  length < key:
py>            for i in range(length, key +1):
py>                self.__list.append(None)
py>        self.__list[key] = value
py>    def __str__(self):
py>        return str(self.__list)
py>
py>x = llist()
py>x[10] = 1
py>print x
[None, None, None, None, None, None, None, None, None, None, 1]

for other methods to add to the llist class see http://docs.python.org/
ref/sequence-types.html




More information about the Python-list mailing list