Not asking particularly about the slicing, Basically I want to replace the value of specific index of list by 2 or more elements.
For Example:
list_a = [1, 2, 3]
and list_b = [4, 5]
so what I want is result = [4, 5, 2, 3]
Not asking particularly about the slicing, Basically I want to replace the value of specific index of list by 2 or more elements.
For Example:
list_a = [1, 2, 3]
and list_b = [4, 5]
so what I want is result = [4, 5, 2, 3]
If you want a new list:
idx = 0
result = list_a[:idx]+list_b+list_a[idx+1:]
Output: [4, 5, 2, 3]
If you want to modify the list in place:
idx = 0
list_a[:] = list_a[:idx]+list_b+list_a[idx+1:]
# OR (see @Nineteendo's comment)
list_a[idx:idx + 1] = list_b
# get values up to the insertion point
list_a[:idx]
# []
# get values after the insertion point
list_a[idx+1:]
# [2, 3]
# combine everything in a single list
list_a[:idx]+list_b+list_a[idx+1:]
# [4, 5, 2, 3]
You can achieve this using below,
First you need to pop 0
index value, then try to reverse the b
and loop over to insert values of b in 0
index of a
a = [1, 2, 3]
b = [4, 5]
a.pop(0)
for i in b.reverse():
a.insert(0, i)
print(a)
Output:
[4, 5, 2, 3]