Python Practice › List Programs › Program 2
Combine two lists
Write a Python program to combine two lists.
Input
[1, 2, 3], [4, 5, 6]
Output
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
Approach
+creates a new list;extend()adds to an existing one.
Solution
list1 = [1, 2, 3]list2 = [4, 5, 6]print(list1 + list2)list1.extend(list2)print(list1)Output
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
Line by line
Line 3
+ returns a new list and leaves both originals unchanged.
Line 4
extend changes list1 in place.
Learn the concept
New to this topic? Read the lesson, then come back.