Tutorial :Simultaneously inserting and extending a list?



Question:

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']  


Solution:1

>>> 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']  >>>  


Solution:2

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']  


Solution:3

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()  


Solution:4

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »