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?
To extend a list, you just use list. extend . To insert elements from any iterable at an index, you can use slice assignment...
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.
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]
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"
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]
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