in this tutorial, We’ll concatenate two lists in python in different ways.We’ll learn how to concatenate lists using ‘+’, ‘*’, extend() etc.
You can also checkout other python list tutorials:
- Check Element Exist in List
- How to Filter a List in Python
- Python Join List Example
- Python List Example And Methods
- How To Compare Python Two Lists
- How To Match String Item into List Python
Method 1: Concatenate Using + Operator
We traverse the second list of items and appending elements in the first list. The first list has all items of the second list.
# Initializing lists list1 = [7, 8, 9, 2] list2 = [10, 11, 12] # using + operator to concat list = list1 + list2 # Printing concatenated list print ("Concatenated list : " + str(list))
Output:Concatenated list : [7, 8, 9, 2, 10, 11, 12]
Method 2: Concatenate Using * Operator
The *list function unpacks a list’s contents. We can unpack the contents of both lists and merge the contents into a new list.
# Initializing lists list1 = [2, 7, 8, 9] list2 = [10, 11, 12] # using * operator to concat list = [*list1, *list2] # Printing concatenated list print ("Concatenated list : " + str(list))
Output:
Concatenated list : [2, 7, 8, 9, 10, 11, 12]
Method 3: Concatenate Using extend
We can also concatenate list using list.extend()
method. The extend()
method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.
# Initializing lists list1 = [7, 8, 9] list2 = [10, 11, 12, 13] # extend to concat list1.extend(list2) # Printing concatenated list print ("Concatenated list : "+ str(list1))
Output:
Concatenated list : [7, 8, 9, 10, 11, 12, 13]
Methos 4: Using Iteraion
We traverse the second list of items and appending elements in the first list. The first list has all items of the second list.
# Initializing lists list1 = [7, 8, 9] list2 = [10, 11, 12] # using simple method to concat for i in list2 : list1.append(i) # Printing concatenated list print ("Concatenated list : " + str(list1))
Output:
Concatenated list : [7, 8, 9, 10, 11, 12]