Reputation: 21961
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]
Upvotes: 1
Views: 94
Reputation: 3461
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]
Upvotes: 1
Reputation: 368894
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]
Upvotes: 7
Reputation: 15071
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:]
Upvotes: 3