add elements to indexed list locations

Steven Bethard steven.bethard at gmail.com
Fri Jun 16 13:46:56 EDT 2006


leventyilmaz at gmail.com wrote:
> # I have a list of names:
> names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
> 
> # and another set of names that I want to insert into
> # the names list at some indexed locations:
> surnames = { 1: 'kent', 3:'parker', 5:'wayne' }
> 
> # The thing I couldn't figure out is, after I insert a
> # surname the rest of the indices are not valid.
> # That is, the following won't work:
> for i, x in surnames.iteritems():
>    names.insert(i,surnames[i])

This seems to work (tested only with what you see below)::

     >>> names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
     >>> surnames = {1:'kent', 3:'parker', 5:'wayne'}
     >>> for index in sorted(surnames, reverse=True):
     ...     names.insert(index, surnames[index])
     ...
     >>> names
     ['clark', 'kent', 'super', 'peter', 'parker', 'spider', 'bruce',
     'wayne', 'bat']

I just did the inserts from right to left, that is, starting at the end. 
  That way, after an insert, I don't have to adjust any indices.

You may also find that if you do a lot of inserts into the list, it may 
be more efficient to create a new list, e.g.::

     >>> names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
     >>> surnames = {1:'kent', 3:'parker', 5:'wayne'}
     >>> new_names = []
     >>> for i, name in enumerate(names):
     ...     if i in surnames:
     ...         new_names.append(surnames[i])
     ...     new_names.append(name)
     ...
     >>> new_names
     ['clark', 'kent', 'super', 'peter', 'parker', 'spider', 'bruce',
     'wayne', 'bat']


STeVe



More information about the Python-list mailing list