Concatenation of lists in Python refers to merging of elements from two or more lists into a single list. Python provides a variety of methods for list concatenation, allowing flexibility based on the requirements of each task.
For all topics related to lists, check out the Lists in Python: A Comprehensive Guide guide.
In the previous article List Slicing in Python, we learned about slicing of list in Python. In this article we will discuss about concatenation of list in Python and how slicing can be used with concatenation to merge only selected elements from one list with another.
What is Concatenation of Lists?
In Python, multiple methods are available for list concatenation, each suited for different scenarios:
- Concatenate using
+
operator - Concatenate using
operator.add()
- Concatenate using
itertools.chain()
- Concatenate using
extend()
method - Concatenate using packing & unpacking with
*
Let’s explore these concatenation methods in detail.
+
Operator
Concatenate Lists using the The +
operator is a simple and commonly used method to concatenate lists in Python. It is like extension of one list elements with another list elements. Following is the syntax:
concat_list = list_1 + list_2
- The
+
operator combines elements in the specified order without modifying the original lists. - In this case, list_1 elements will be first and then list_2 elements will be merged in the concatenated list.
- Original lists will remain same. Like there will be no change in list_1 and list_2 elements.
- Compatible with any element type within lists.
+
Operator
Program – Concatenate Lists using the # Concatenate Lists using the + Operator
print("Concatenate using '+' operator")
x = ["Python", "Java", "AWS", "Azure"]
y = [10,20,30]
z = x + y # Concatenate list using '+' operator
print("x - ", x)
print("y - ", y)
print("z - ", z) # Print concatenated list
In this program, we are have defined 2 lists which are referenced by variables x
and y
. We are using +
operator to concatenate lists and assigning the concatenated list with variable z
. There will be no change in the elements of list x
and y
.
Output – Example Program – Concatenate Lists using the + Operator
Concatenate using '+' operator
x - ['Python', 'Java', 'AWS', 'Azure']
y - [10, 20, 30]
z - ['Python', 'Java', 'AWS', 'Azure', 10, 20, 30]
From the output, concatenated list z
has elements merged from both lists. Elements from list x
are first and then elements of list y
are merged. No change in elements of lists x
and y
.
operator.add()
Concatenate Lists using The Python operator
module provides an add()
method for list concatenation. operator
is Python’s built-in module. Following is the syntax:
concat_list = operator.add(list_1, list_2)
operator.add(list_1, list_2)
will merge all the elements of all the lists given for concatenation.- Elements are merged in the order specified with no change to the original lists.
- Original lists will remain same i.e. there will be no change in
list_1
andlist_2
elements. - Compatible with any element type within lists.
operator.add()
Program – Concatenate Lists using # Concatenate Lists using operator.add()
print("Concatenate using operator plugin")
import operator # Import operator module
a = [5,6,8]
b = ["C", "C++", "Java", "Python"]
c = operator.add(a,b) # Concatenate list using operator.add method
print("a - ", a)
print("b - ", b)
print("c - ", c) # Print concatenated list
Before using any module, we need to import that module in the program. In this program we are importing operator
module. We have defined 2 lists which are referenced by variables a
and b
. We are using operator.add()
method to concatenate lists and referencing the concatenated list with variable c
.
Output – Example Program – Concatenate Lists using operator.add()
Concatenate using operator plugin
a - [5, 6, 8]
b - ['C', 'C++', 'Java', 'Python']
c - [5, 6, 8, 'C', 'C++', 'Java', 'Python']
From the program output, concatenated list c
has elements merged from both lists. Elements from list a
are ordered first and then elements of list b
are merged. No change in elements of lists a
and b
.
itertools.chain()
Concatenate Lists using The itertools
module includes the chain()
method, which concatenates lists by iterating over their elements. itertools
is Python’s built-in module. This module can be used to iterate through the collections like list, tuple, set, dictionary etc. This function also returns an iterator.
Syntax to concatenate lists using itertools.chain()
concat_list = list(itertools.chain(list_1, list_2))
itertools.chain()
returns an iterator, to iterate through all element of the lists.- We can use the list constructor to construct a list through the iterated elements.
- All elements of both lists will be iterated and collected in the given order
- Original lists will remain same i.e. there will be no change in
list_1
andlist_2
elements.
itertools.chain()
Program – Concatenate Lists using #Concatenate Lists using itertools.chain()
print("Concatenate Lists using itertools.chain()")
import itertools # Import itertools module
x = ["Python", "Java", "AWS", "Azure"]
y = [10,20,30]
z = list(itertools.chain(x, y)) # Concatenate list using itertools.chain
print("x - ", x)
print("y - ", y)
print("z - ", z) # Print concatenated list
We have imported itertools
module in the program. We are using itertools.chain()
method to create an iterator over the given lists. Iterator iterate through the elements of both the lists. Iterated elements are collected as a list using list constructor. This gives us concatenated list which is reference by variable z
.
Output – Example Program – Concatenate Lists using itertools.chain()
Concatenate Lists using itertools.chain()
x - ['Python', 'Java', 'AWS', 'Azure']
y - [10, 20, 30]
z - ['Python', 'Java', 'AWS', 'Azure', 10, 20, 30]
From the program output, concatenated list z
has elements merged from both lists. Elements from list x
are ordered first and then elements of list y
are merged. No change in elements of lists x
and y
.
extend()
method
Concatenate Lists using Python’s extend()
method adds elements from one list to another. extend()
method to extend (merge) the elements of a list with another list. Syntax of using extend()
method:
list_1.extend(list_2)
- Adds all elements from
list_2
tolist_1
i.e all elements oflist_2
will be added tolist_1
. - Alters
list_1
directly without creating a new list. extend()
method does not return any new list.
extend()
method
Program – Concatenate Lists using # Concatenate Lists using extend(() method
print("Concatenate Lists using extend(() method")
x = ["Python", "NumPy", "Pandas", "Scikit-learn"]
y = [40, 50, 60]
print("x - ", x)
print("y - ", y) # Print defined lists x and y
y.extend(x) # extend list y with elements of list x
print("y - ", y) # Print concatenated list
We have defined two lists x
and y
. Then we are using extend()
method on list y
. List x
elements will be merged to list y
Output – Example Program – Concatenate Lists using extend() method
Concatenate Lists using extend(() method
x - ['Python', 'NumPy', 'Pandas', 'Scikit-learn']
y - [40, 50, 60]
y - [40, 50, 60, 'Python', 'NumPy', 'Pandas', 'Scikit-learn']
Originally, list y
was defined with 3 elements. But after using extend()
method, it has merged elements of list x
as well.
*
)
Concatenate Lists Using Packing & Unpacking (In Python the *
operator allows packing & unpacking elements from multiple lists into a new list. Syntax of using *
operator:
concat_list = [*list_1, *list_2]
- Unpacks elements into a new list without modifying the original lists.
- Using
*
operator, elements oflist_1
andlist_2
are unpacked and then collected into concatenated list. - Original lists will remain same i.e. there will be no change in
list_1
andlist_2
elements.
*
)
Program – Concatenate Lists Using Packing & Unpacking (# unpacking - (*k, *l) - using asterisk*
print("unpacking - [*k, *l] - using asterisk*")
k = [55,60,89]
l = ["AWS", "Azure", "C++", "Java"] # Print defined lists k and l
m = [*k , *l] # unpack and collect elements
print("k - ", k)
print("l - ", l)
print("m - ", m) # Print concatenated list
Using *
operator with list k
and l
=> [*k , *l]
– Lists k
and l
are unpacked and their elements are collected again as a concatenated list referenced by variable m
.
Output – Example Program – Concatenate Lists Using Packing & Unpacking (*)
unpacking - [*k, *l] - using asterisk*
k - [55, 60, 89]
l - ['AWS', 'Azure', 'C++', 'Java']
m - [55, 60, 89, 'AWS', 'Azure', 'C++', 'Java']
Summary
This guide explored different methods to concatenate lists in Python, including the +
operator, operator.add()
, itertools.chain()
, extend()
, and unpacking with *
. Each method provides unique benefits, depending on whether you want to modify the original lists or create a new one.
Code snippets and programs related to Concatenate List in Python, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
+
operator and the extend()
method to concatenate lists?
Q: What is the difference between using the The main difference between the +
operator and the extend()
method lies in memory usage and how they handle the original lists:
- Memory Usage – The
+
operator creates a new list, leaving the original lists unchanged, which consumes more memory. - This approach is helpful when you need to preserve the original lists.
list_1 = [12, 22, 34]
list_2 = [44, 56, 64]
concat_list = list_1 + list_2 # concat_list is a new list
- In-Place Modification – The
extend()
method modifies the original list in place, making it more memory-efficient by avoiding the creation of a new list. - This is useful when we want to avoid creating a new list
list_1 = [12, 22, 34]
list_1.extend([44, 56, 64]) # updated elements of list_1
+
operator and extend()
method impact the large-scale applications?
Q: How the performance for concatenation of lists using Memory and Time Complexity of Concatenation Using +
Operator and extend()
Method:
+
Operator to Concatenate Lists – Python creates a new list and copies the elements from both original lists into this new list. This operation has a time complexity ofO(n + m)
, wheren
andm
are the lengths of the two lists. Additionally, because it creates a new list, it requires more memory.extend()
Method to Concatenate Lists – Theextend()
method modifies the list in place and has a time complexity ofO(m)
, wherem
is the length of the list to be added. This method is more efficient in terms of both time and memory, especially for large lists.
Example Program to compare the time taken for concatenation using +
operator and extend()
method
import time
list_1 = list(range(1000000))
list_2 = list(range(1000000))
# Using the + operator
start = time.time()
concat_list = list_1 + list_2
print(f"Time taken using +: {time.time() - start} seconds")
# Using extend()
start = time.time()
list_1.extend(list_2)
print(f"Time taken using extend: {time.time() - start} seconds")
From the program output, we will observe that the extend()
method is faster and more memory-efficient than the +
operator.
Points to consider for Large-Scale Applications:
- Memory Efficiency – In memory-constrained environments, prefer
extend()
over+
to avoid unnecessary memory usage. - Performance – For large lists,
extend()
is generally faster as it avoids the overhead of creating a new list and copying all elements.
+
or extend()
?
Q: In Python, what will be the performance impact of concatenate lists using loops compare to using We can concatenate lists using loops, but it is generally less efficient than using the +
operator or extend()
method.
Example Program to Concatenate Elements Using a Loop:
list_1 = [15, 25, 35]
list_2 = [48, 58, 68]
for item in list_2:
list_1.append(item)
print(list_1) # Elements in list_1: [15, 25, 35, 48, 58, 68]
- Performance – Looping through elements and appending them individually is slower than using
extend()
, especially for large lists. - Code Readability – Using
extend()
or+
is more simpler and clean code and easier to understand. - Flexibility – Using loop we have more flexibility. If can apply some transformation to elements before appending.
If no transformations are needed before concatenation, using the extend() method or + operator is generally better for performance and code clarity.
Related Topics
- Understanding Lists in Python: A Comprehensive GuideLists in Python List is a core datatype in Python. Lists are sequences used to store elements (collection of data). Lists are similar to Arrays but are of dynamic size. It means the size of the list can be increased or decreased as we add or remove elements from the list. Understanding Python Lists: A…
- How to Create List in Python | Python List Creation Methods ExplainedList is a sequence data type used to store elements (collection of data). Lists are similar to Arrays but have a dynamic size, meaning the list size can increase or decrease as elements are added or removed. A list is a core data type in Python, along with Tuple, Set and Dictionary. Lists in Python…
- How to Access List Elements by Index in Python (with Example Programs)Python list elements are stored based on their index positions and can be accessed by their index positions, which allows to quickly retrieve specific element from the list. Index assignment to list element in Python, is similar to index assigned in Array elements. Understanding how to access list elements by index is crucial for data…
- Python List Index Method Explained with Examples | Get Element Position in ListElements in a Python list are stored based on their index positions. Lists in Python provides an index(arg) method to get the index position of an element within a list. In the previous article How to Access List Elements by Index, we learned how to access a list element using its index position. In this…
- Append Elements to List – Python | Add Elements with Append MethodIn Python, elements in a list can be added using the append(element) method. This method allows us to add elements to the end of a list easily. In the previous articles, we explored accessing list elements by index and using the list index method to retrieve an element’s position. This article covers appending new elements…