Hey guys, in this blog we will see a Python Program to Concatenate Two Lists.
Example 1: Using + operator
list_1 = [1, 'a'] list_2 = [3, 4, 5] list_joined = list_1 + list_2 print(list_joined)
Output
[1, ‘a’, 3, 4, 5]
- + operator can be used to simply join 2 lists.
Example 2: Using iterable unpacking operator *
list_1 = [1, 'a'] list_2 = range(2, 4) list_joined = [*list_1, *list_2] print(list_joined)
Output
[1, ‘a’, 2, 3]
- * is used to unpack all the items of an iterable.
- Here we have unpacked the elements of both lists in a new list.
Example 3: With unique values
list_1 = [1, 'a'] list_2 = [1, 2, 3] list_joined = list(set(list_1 + list_2)) print(list_joined)
Output
[1, 2, 3, 'a']
- Here also we used + operator to merge two lists and then we converted it to a set to eliminate all the duplicate values.
- Then again we are converting it back to a list.
Example 4: Using extend()
list_1 = [1, 'a'] list_2 = [1, 2, 3] list_2.extend(list_1) print(list_2)
Output
[1, 2, 3, 1, ‘a’]
- All lists have an inbuilt function called extend() which is used to add a new list to the current list.
Check out our other python programming examples…