Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously inserting and extending a list?

Tags:

python

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']
like image 245
klozovin Avatar asked Mar 16 '09 21:03

klozovin


People also ask

What are append () and extend () list methods?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

What is the difference between list methods append () and extend ()?

To recap, the difference between append() and extend() methods is: The append() method adds a single element to a list. The extend() method adds multiple elements to a list.

How do you add multiple lists at once?

Using + operator to append multiple lists at once This can be easily done using the plus operator as it does the element addition at the back of the list. Similar logic is extended in the case of multiple lists.

What is the difference between pop () and append () function of list?

pop() to remove an item from ListA and then use . append() to add it to ListB.


1 Answers

>>> 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']
>>>
like image 162
Markus Jarderot Avatar answered Oct 21 '22 09:10

Markus Jarderot