add elements to indexed list locations

Diez B. Roggisch deets at nospam.web.de
Fri Jun 16 13:44:49 EDT 2006


leventyilmaz at gmail.com schrieb:
> Hi,
> 
> I have a very simple problem, but do not know an elegant way to
> accomplish this.
> ###
> # 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])
> ###
> 
> I am searching a nice way to do this. For instance, is there a more
> robust way to store indices (as some sort of pointers maybe?) 

Use a dictionary for both of them?

The concept of indices is that they IMPLY a position. So either you work 
in a way that you e.g. add the surnames in a defined order and adjust 
the subsequent indices, or you discard the approach entirely and e.g use 
a map of first to surnames.

Diez



More information about the Python-list mailing list