#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    14
    Rep Power
    0

    How to Insert Elements Anywhere in a List?


    Hello,

    I would like to create a list (don't know the length beforehand) by inserting elements non-consecutively. In other words, I don't want to insert 0, 1, 2..., but instead insert elements 50, 2, 10, etc. Is this possible? This would leave list elements empty between other elements that have been inserted.

    I have tried this in my code, but it doesn't appear to do what I hope.

    Thanks for any help.

    -John
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,897
    Rep Power
    481
    Code:
    >>> class mylist(list):
    ...     def __init__(self, iterable = [], null_value = 'unassigned'):
    ...         super(self.__class__, self).__init__(iterable)
    ...         self.null_value = null_value
    ...     def __setitem__(self, item, value):
    ...         if len(self) <= item:
    ...             self.extend([self.null_value]*(1+item-len(self)))
    ...         super(self.__class__, self).__setitem__(item, value)
    ... 
    >>> 
    >>> L = yourlist()
    >>> L = mylist()
    >>> L[12] = '$12^{th}$ item'
    >>> L[2] = 'second item'
    >>> L[10] = 'tenth'
    >>> import pprint
    >>> pprint.pprint(L)
    ['unassigned',
     'unassigned',
     'second item',
     'unassigned',
     'unassigned',
     'unassigned',
     'unassigned',
     'unassigned',
     'unassigned',
     'unassigned',
     'tenth',
     'unassigned',
     '$12^{th}$ item']
    >>>
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo