Given two lists:
x = [1,2,3] y = [4,5,6]
What is the syntax to:
- Insert
xintoysuch thatynow looks like[1, 2, 3, [4, 5, 6]]? - Insert all the items of
xintoysuch thatynow looks like[1, 2, 3, 4, 5, 6]?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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]
Method 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]
Method 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
Method 4
If you want to add the elements in a list (list2) to the end of other list (list), then you can use the list extend method
list = [1, 2, 3] list2 = [4, 5, 6] list.extend(list2) print list [1, 2, 3, 4, 5, 6]
Or if you want to concatenate two list then you can use + sign
list3 = list + list2 print list3 [1, 2, 3, 4, 5, 6]
Method 5
You can also just do…
x += y
Method 6
If we just do x.append(y), y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:
x = [1,2,3]
y = [4,5,6]
x.append(y[:])
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0