Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extend list with another list in specific index?

In python we can add lists to each other with the extend() method but it adds the second list at the end of the first list.

lst1 = [1, 4, 5]
lst2 = [2, 3]

lst1.extend(lst2)

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

How would I add the second list to be apart of the 1st element? Such that the result is this;

[1, 2, 3, 4, 5 ]

I’ve tried using lst1.insert(1, *lst2) and got an error;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: insert expected 2 arguments, got 3

>Solution :

For those who don’t like reading comments:

lst1 = [1, 4, 5]
lst2 = [2, 3]

lst1[1:1] = lst2
print(lst1)

Output:

[1, 2, 3, 4, 5]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading