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.
Usingextend()
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.
a = [1, 2, 3]
n = [4, 5, 6]
a.extend(n)
print(a)
[1, 2, 3, 4, 5, 6]
Explanation:
extend()
method directly modifies the original list by adding all elements from n
at the end.Let's explore some more ways of extending a list in Python.
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.
a = [1, 2, 3]
n = [4, 5, 6]
a += n
print(a)
[1, 2, 3, 4, 5, 6]
Explanation:
+=
operator adds all the elements of 'n'
to the list 'a'
.We can use slicing with [:]
to replace or extend the content of a list. It modifies the original list in-place, similar to extend()
.
a = [1, 2, 3]
b = [4, 5, 6]
# Extending list 'a' using slicing
a[len(a):] = b
print(a)
[1, 2, 3, 4, 5, 6]
Explanation:
a[len(a):]
represents the slice starting at the end of the list.b
to this slice effectively appends all elements of b
to a
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.
from itertools import chain
a = [1, 2, 3]
n = [4, 5, 6]
a.extend(chain(n))
print(a)
[1, 2, 3, 4, 5, 6]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4