How to insert multiple elements into a list?

Question:

In JavaScript, I can use splice to insert an array of multiple elements in to an array: myArray.splice(insertIndex, removeNElements, ...insertThese).

But I can’t seem to find a way to do something similar in Python without having concat lists. Is there such a way? (There is already a Q&A about inserting single items, rather than multiple.)

For example myList = [1, 2, 3] and I want to insert otherList = [4, 5, 6] by calling myList.someMethod(1, otherList) to get [1, 4, 5, 6, 2, 3]

Asked By: TheRealFakeNews

||

Answers:

To extend a list, you just use list.extend. To insert elements from any iterable at an index, you can use slice assignment…

>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[5:5] = range(10, 13)
>>> a
[0, 1, 2, 3, 4, 10, 11, 12, 5, 6, 7, 8, 9]
Answered By: mgilson

Python lists do not have such a method. Here is helper function that takes two lists and places the second list into the first list at the specified position:

def insert_position(position, list1, list2):
    return list1[:position] + list2 + list1[position:]
Answered By: RFV

The following accomplishes this while avoiding creation of a new list. However I still prefer @RFV5s method.

def insert_to_list(original_list, new_list, index):
    
    tmp_list = []
    
    # Remove everything following the insertion point
    while len(original_list) > index:
        tmp_list.append(original_list.pop())
    
    # Insert the new values
    original_list.extend(new_list)
    
    # Reattach the removed values
    original_list.extend(tmp_list[::-1])
    
    return original_list

Note that it’s necessary to reverse the order of tmp_list because pop() gives up the values from original_list backwards from the end.

Answered By: corvus

use listname.extend([val1,val2,val,etc])

I’m not certain this question is still being followed but I recently wrote a short code that resembles what is being asked here. I was writing an interactive script to perform some analyses so I had a series of inputs serving to read in certain columns from a CSV:

X = input('X COLUMN NAME?:n')
Y = input('Y COLUMN NAME?:n')
Z = input('Z COLUMN NAME?:n')
cols = [X,Y,Z]

Then, I brought the for-loop into 1 line to read into the desired index position:

[cols.insert(len(cols),x) for x in input('ENTER COLUMN NAMES (COMMA SEPARATED):n').split(', ')]

This may not necessarily be as concise as it could be (I would love to know what might work even better!) but this might clean some of the code up.

Answered By: William Taylor

The python equivalent of JavaScript

myArray.splice(insertIndex, removeNElements, ...insertThese) 

would be:

my_list[insert_index:insert_index + remove_n_elements] = insert_these
Answered By: Bjorkegeek
Modifying the solution shared by RFV in earlier post.
Solution:
list1=list1[:position] + list2 + list1[position:]
    
Ex: Trying to insert the list of items at the 3rd index(2 is used in code snippet as positive indexing starts from 0 in Python)

list1=[0,1,23,345.22,True,"Data"] 
print(type(list1))
print(list1)
list2=[2,3,4,5]
list1=list1[:2] + list2 + list1[2:]
print("After insertion the values are",list1)
    
Ouput for the above code snippet.
<class 'list'>
[0, 1, 23, 345.22, True, 'Data']
After insertion the values are [0, 1, 2, 3, 4, 5, 23, 345.22, True, 'Data']
Answered By: Madhu Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.