Add elements of one list at the end of another list in python
Answers
Answer:
Appending one list to another results in a list that contains all the values of the first and second list. For example, a list [3, 4] appended to [1, 2] will result in the combined [1, 2, 3, 4]. A list can also be appended as an element to produce a list inside of a list such as [1, 2, [3, 4]].
USE list.extend() TO COMBINE TWO LISTS
Use the syntax list1.extend(list2) to combine list1 and list2.
list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)
Combine list1 and list2
print(list1)
OUTPUT
[1, 2, 3, 4]
USE list.append() TO ADD A LIST INSIDE OF A LIST
Use the syntax list1.append(list2) to add list2 to list1.
list1 = [1, 2]
list2 = [3, 4]
list1.append(list2)
Add list2 to list1
print(list1)
OUTPUT
[1, 2, [3, 4]]
OTHER SOLUTIONS
Use itertools.chain() to combine many lists
This solution is more efficient because it avoids copying the lists.
Further reading: See documentation for itertools.chain()
Explanation: