Home > Software engineering >  how to insert a list in between of another list in python
how to insert a list in between of another list in python

Time:10-09

suppose i have an array like

name = ["aadarsh","shivam","divyam","hariyam"];

now i want to add an array in between of the above array and that array is

other_names = ["slogan","moghan"]

and lets say i wanna insert after the second index of the 'name' array and want to print like below one

"aadarsh","shivam","divyam","slogan","moghan","hariyam"

but as soon as i am using insert function like the below one

name.insert(2,other_names)

then it is printing in the below format

"aadarsh","shivam","divyam",["slogan","moghan"], "hariyam"

if i do name[3] then it is printing the whole 'other_names' array. where as i want that name[3]

should be slogan and a[4] should be moghan only.

is there any way to make the 'other_names array to be the part of 'name' array as each elements of

'other_names' array should have its own index number continuing with 'name' array index numbers

CodePudding user response:

You can try this

name = ["aadarsh","shivam","divyam","hariyam"]
other_names = ["slogan","moghan"]
name[pos:pos] = other_names #pos=the position at which you want to insert. here it is 3
print(name)

Output

['aadarsh', 'shivam', 'divyam', 'slogan', 'moghan', 'hariyam']

CodePudding user response:

You can use slicing:

name = ["aadarsh","shivam","divyam","hariyam"]
other_names = ["slogan","moghan"]

def extend_after(values, values_to_add, idx):
    return values[:idx   1]   values_to_add   values[idx   1:]

output = extend_after(name, other_names, 2)

CodePudding user response:

You can create a function that will add each value to the list you want.

def append_list(index, receiving_list, appended_list):
     for item in appended_list[::-1]:
             receiving_list.insert(index, item)

Result:

>>> name = ["aadarsh","shivam","divyam","hariyam"]
>>> other_names = ["slogan","moghan"]

>>> append_list(2, name, other_names)
>>> name
['aadarsh', 'shivam', 'slogan', 'moghan', 'divyam', 'hariyam']

CodePudding user response:

You can try this

name = ["aadarsh","shivam","divyam","hariyam"]

other_names = ["slogan","moghan"]

for each in other_names:

    name.insert(-2,each)

print(name)

CodePudding user response:

your problem will simply solved by for loop with insert method

name = ["aadarsh","shivam","divyam","hariyam"]

other_names = ["slogan","moghan"]

for other_name in other_names:
    name.insert(3, other_name)

print(name)
  • Related