How to insert multiple elements into a list?

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

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.


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]