-1

For example, how do i do this:

x=[1,2,3]
y=[4,5,6]
list3=[1,4,5,6,2,3]

i do not want [1,[4,5,6],2,3]

basically i want to extend it, but at a given index

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • What code have you written to give you the unwanted result? –  Aug 22 '21 at 18:20
  • Does this answer your question? [How to insert multiple elements into a list?](https://stackoverflow.com/questions/39541370/how-to-insert-multiple-elements-into-a-list) – wjandrea Aug 22 '21 at 18:22
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. This is a nice first question, though it'd be even better if you had done your own research first. I found the above question by googling `python insert multiple items into list`. – wjandrea Aug 22 '21 at 18:23
  • i used list.insert(index,list2) to insert the 2nd list at given index, but i need it to be inserted as individual integers, not collectively as a list – Keshav Nair Aug 22 '21 at 18:23
  • Welcome to Stack Overflow. Please add minimal reproducible example, or at least an attempt. See https://stackoverflow.com/help/how-to-ask – cards Aug 22 '21 at 21:58

2 Answers2

3

Select an empty slice at the index you want, and insert the other list there:

>>> x=[1,2,3]
>>> y=[4,5,6]
>>> x[1:1]=y
>>> x
[1, 4, 5, 6, 2, 3]
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

Use slice assignment.

list3 = x[:] # make copy of x
list3[1:1] = y # replace empty slice at index 1 
Barmar
  • 741,623
  • 53
  • 500
  • 612