Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple values by index into list at one time

I was wondering if there was a way to insert multiple variables into a list at one time using the same index. So for example, let's say we have a list of

[a, b, c]

and

[0,1,2,3,4]

and I wanted to insert the first list such that the end result is,

[a, 0, 1, b, 2, 3, c, 4]

But if I was going to do it individually using list.insert(pos, value)and used the positions of [0, 2, 4] then the subsequent positions used becomes invalid since it was relating to the old list of 5 elements instead of 6 now.

Any suggestions?

like image 370
Loc-Tran Avatar asked May 23 '16 05:05

Loc-Tran


People also ask

Which of the following method is used to insert multiple elements into the list?

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

How do I append to a specific index list?

Inserting an element in list at specific index using list. insert() In python list provides a member function insert() i.e. It accepts a position and an element and inserts the element at given position in the list.


3 Answers

list_a = [0,1,2,3,4]
list_b = ["a", "b", "c"]
pos    = [0, 2, 4]

assert(len(list_b) == len(pos))
acc = 0
for i in range(len(list_b)):
    list_a.insert(pos[i]+acc, list_b[i])
    acc += 1

print(list_a)

['a', 0, 1, 'b', 2, 3, 'c', 4]

like image 59
Rahn Avatar answered Oct 05 '22 14:10

Rahn


One simple option is to add the items starting with the position with highest value, and then continue with the 2nd highest value, etc.

This way you can using the original method, without any problem of "old/new position"

like image 37
Yaron Avatar answered Oct 05 '22 15:10

Yaron


One ways without using a list comprehension:

>>> a = [0,1,2,3,4]
>>> b = ['a', 'b', 'c']
>>> ind = [0, 2, 4]
>>> d = dict(zip(ind, b))

>>> [t for k in [(d.get(i),j) for i,j in enumerate(a)] for t in k if t is not None]
['a', 0, 1, 'b', 2, 3, 'c', 4]
like image 34
Mazdak Avatar answered Oct 05 '22 16:10

Mazdak