Extending a list in Python (original) (raw)
Last Updated : 17 Dec, 2024
In Python, a list is one of the most widely used data structures for storing multiple items in a single variable. Often, we need to extend a list by adding one or more elements, either from another list or other iterable objects. Python provides several ways to achieve this. In this article, we will explore different methods to extend a list.
Using extend()
extend() method is the most efficient way to add multiple elements to a list. It takes an iterable (like a list, tuple, or set) and appends each of its elements to the existing list.
Python `
a = [1, 2, 3] n = [4, 5, 6]
a.extend(n) print(a)
`
**Explanation:
- The
extend()
method directly modifies the original list by adding all elements fromn
at the end. - It works in-place and avoids creating a new list, making it highly efficient.
Let's explore some more ways of extending a list in Python.
Table of Content
Using the +=
Operator
The += operator can be used to extend a list. Internally, it works similarly to the extend()
method but provides a more concise syntax.
Python `
a = [1, 2, 3] n = [4, 5, 6]
a += n print(a)
`
**Explanation:
- The
+=
operator adds all the elements of 'n'
to the list'a'
. - It works in-place and avoids creating a new list.
**Using slicing
We can use slicing with [:]
to replace or extend the content of a list. It modifies the original list **in-place, similar to extend()
.
Python `
a = [1, 2, 3] b = [4, 5, 6]
Extending list 'a' using slicing
a[len(a):] = b
print(a)
`
**Explanation:
a[len(a):]
represents the slice starting **at the end of the list.- Assigning
b
to this slice effectively **appends all elements ofb
toa
in-place.
NOTE: **slicing in Python can be used to insert values at specific positions in a list, for instance, using
a[:0],
the values are added **at the beginning of the list.
The itertools.chain() method combines multiple iterables into one continuous sequence, which can be converted to a list or extended into an existing list.
Python `
from itertools import chain
a = [1, 2, 3] n = [4, 5, 6] a.extend(chain(n)) print(a)
`