What is the syntax to insert one list into another list in python?
Given two lists:
x = [1,2,3]
y = [4,5,6]
What is the syntax to:
- Insert
x
intoy
such thaty
now looks like[1, 2, 3, [4, 5, 6]]
? - Insert all the items of
x
intoy
such thaty
now looks like[1, 2, 3, 4, 5, 6]
?
Solution 1:
Do you mean append
?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]
Or merge?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]
Solution 2:
The question does not make clear what exactly you want to achieve.
List has the append
method, which appends its argument to the list:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]
There's also the extend
method, which appends items from the list you pass as an argument:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]
And of course, there's the insert
method which acts similarly to append
but allows you to specify the insertion point:
>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]
To extend a list at a specific insertion point you can use list slicing (thanks, @florisla):
>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]
List slicing is quite flexible as it allows to replace a range of entries in a list with a range of entries from another list:
>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]
Solution 3:
foo = [1, 2, 3]
bar = [4, 5, 6]
foo.append(bar) --> [1, 2, 3, [4, 5, 6]]
foo.extend(bar) --> [1, 2, 3, 4, 5, 6]
http://docs.python.org/tutorial/datastructures.html
Solution 4:
You can also just do...
x += y