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']
append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.
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.
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.
pop() to remove an item from ListA and then use . append() to add it to ListB.
>>> 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']
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With