1

How do I insert one list fully inside another python list?

>>> list_one = [1,2,3]
>>> list_two = [4,5,7]

>>> list_one.insert(2, [2, 3])
>>> list_one
[1, 2, [2, 3], 3, 4, 5, 7]

But I want the result to be:

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

3 Answers 3

7

Using slice assignment (if you meant [1,2,4,5,6,3]):

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one[2:2] = list_two
>>> list_one
[1, 2, 4, 5, 6, 3]
Sign up to request clarification or add additional context in comments.

2 Comments

Wow! I didn't know that was possible! You learn something new everyday...
@Julien, It's explained in tutorial ( docs.python.org/3/tutorial/introduction.html#lists ). I recommend you to read it if you didn't.
3

Are you sure you don't want this result [1,2,4,5,6,3] instead? If so, try this:

list_one[:2]+list_two+list_one[2:]

Comments

1

You can try this way.

ActivePython 2.7.13.2713 (ActiveState Software Inc.) based on
Python 2.7.13 (default, Jan 18 2017, 15:40:43) [MSC v.1500 64 bit (AMD64)] on wi
n32
Type "help", "copyright", "credits" or "license" for more information.
>>> list_one = [1,2,3]
>>> list_two = [4,5,7]
>>> from itertools import chain
>>> result = [ elem for elem in chain(list_one[0:2], [2,3], list_one[2:], list_two)]
>>>
>>> result
[1, 2, 2, 3, 3, 4, 5, 7]
>>> result1 = list(chain(list_one[0:2], [2,3], list_one[2:], list_two))
>>> result1
[1, 2, 2, 3, 3, 4, 5, 7]

2 Comments

You can use list instead of list comprehension: list(chain(list_one[0:2], [2,3], list_one[2:], list_two))
Yes, We can do that as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.