List Behavior when inserting new items
Gigs_
gigs at hi.t-com.hr
Tue Feb 6 08:02:19 EST 2007
wittempj at hotmail.com wrote:
> 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
>
or like this
>>> class Llist(list):
def __init__(self):
list.__init__(self)
def insertatindex(self, index, value):
lenght = len(self)
if lenght < index:
for i in range(lenght, index):
self.append(None)
self.insert(index, value)
More information about the Python-list
mailing list