Sook Yee Lim Sook Yee Lim - 3 years ago 85
Python Question

How to insert a list at a specific index?

I got a list

a=[1,2,3]


and a list of list

b=[[1,2],[3,4,5]]


and I want to insert a into b at index 1 so b becomes

b=[[1,2],[1,2,3],[3,4,5]]


How do I do that?If I use insert it won't work because I can only insert an item not a list?

EDIT:I realised insert can be used for lists as well.Thanks.

Answer Source

You can use list.insert which takes the index as the first argument

>>> a=[1,2,3]
>>> b=[[1,2],[3,4,5]]
>>> b.insert(1, a)
>>> b
[[1, 2], [1, 2, 3], [3, 4, 5]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download