简体   繁体   中英

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.

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]]

You can use list slicing:

b=[[1,2],[3,4,5]]
a = [1, 2, 3]
final_list = b[:1]+[a]+b[1:]

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM