tags:

views:

169

answers:

4

Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):

>>> a = ['1', '2', '3', '4']
>>> b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'):]
>>> b
<<< ['1', '2', '2.4', '2.6', '3', '4']
+13  A: 
>>> a = ['1', '2', '3', '4']
>>> a
['1', '2', '3', '4']
>>> i = a.index('2') + 1  # after the item '2'
>>> a[i:i] = ['2.4', '2.6']
>>> a
['1', '2', '2.4', '2.6', '3', '4']
>>>
MizardX
+2  A: 

I'm not entirely clear on what you're doing; if you want to add values, and have the list remain in order, it's cleaner (and probably still faster) to just sort the whole thing:

a.extend(['2.4', '2.6'])
a.sort()
DNS
+3  A: 

You can easily insert a single element using list.insert(i, x), which Python defines as s[i:i] = [x].

a = ['1', '2', '3', '4']
for elem in reversed(['2.4', '2.6']):
    a.insert(a.index('2')+1, elem))

If you want to insert a list, you can make your own function that omits the []:

def iextend(lst, i, x):
    lst[i:i] = x

a = ['1', '2', '3', '4']
iextend(a, a.index('2')+1, ['2.4', '2.6']
# a  = ['1', '2', '2.4', '2.6', '3', '4']
zweiterlinde
+2  A: 

Have a look at the bisect module. I think it does what you want.

Georg