The Wayback Machine - https://web.archive.org/web/20240824063531/https://www.geeksforgeeks.org/append-extend-python/
Open In App

append() and extend() in Python

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Extend and Append are two Python list methods used to add elements to a list. Although they appear similar, they have different functionalities and use cases. Understanding the differences between the append() and extend() methods is crucial when working with lists in Python. Although both techniques are used to add elements to a list, their behaviors and effects vary. We will examine the distinctions between append() and extend(), how they are used, and when to pick one over the other in this post.

Extend vs Append Python List Methods

In Python, there are two ways to add elements to a list: extend() and append(). However, these two methods serve quite different functions. In append() we add a single element to the end of a list. In extend() we add multiple elements to a list. The supplied element is added as a single item at the end of the initial list by the append() method. When an Iterable is supplied as a parameter, the extend() method adds each element from the Iterable to the list’s end individually. It alters the initial list.

What is Append in Python?

Python’s append() function inserts a single element into an existing list. The element will be added to the end of the old list rather than being returned to a new list. Adds its argument as a single element to the end of a list. The length of the list increases by one. 

 Syntax of Python append()

Syntax:  list.append(item)
Parameters:

  • item: an item to be added at the end of the list, The parameter is mandatory and omitting it can give an error.

Returns: The method doesn’t return any value

Example 1: Here in this example, we have added an item to an existing list using Python.

Python
my_list = ['geeks', 'for']
my_list.append('geeks')
print my_list

Output

['geeks', 'for', 'geeks']

NOTE: A list is an object. If you append another list onto a list, the parameter list will be a single object at the end of the list. 

Example 2: Here in this example, we have added another list to an existing list using Python.

Python
my_list = ['geeks', 'for', 'geeks']
another_list = [6, 0, 4, 1]
my_list.append(another_list)
print my_list

Output

['geeks', 'for', 'geeks', [6, 0, 4, 1]]

What is extend() in Python? 

The Python’s List extend() Iterates over its argument and adding each element to the list and extending the list. The length of the list increases by a number of elements in its argument.

 Syntax of Python extend()

Syntax: list.extend(iterable)

Parameters:

  • iterable: Any iterable (list, set, tuple, etc.)

Returns: None

Example 1: Here in this example we are extending a list into a existing list using Python.

Python
my_list = ['geeks', 'for']
another_list = [6, 0, 4, 1]
my_list.extend(another_list)
print my_list

Output

['geeks', 'for', 6, 0, 4, 1]

NOTE: A string is iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string. 

Example 2: Here in this example we are extending a given item into a existing list using python.

Python
my_list = ['geeks', 'for', 6, 0, 4, 1]
my_list.extend('geeks')
print my_list

Output

['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']

Difference Between append() and extend() in Python

Basis for Comparison

Append()

Extend()

Purpose


To add a single entry to the end of a list, use the append() function.To add additional elements or an iterable to the end of a list, use the extend() function.

Input

accepts only one input element.

accepts as input an iterable (such as a list or tuple).


Operation


The append() function adds the full input to the list as a single item.



extend() adds each item to the list independently after iterating through each one in the input.


Efficiency


Since append() only executes one operation, it is typically quicker and more effective than extend().


When adding elements from numerous iterables or with huge inputs, extend() could take longer.


Time complexity


Append has constant time complexity i.e.,O(1)


Extend has a time complexity of O(k). Where k is the length of the list which need to be added.

append() and extend() in Python – FAQs

What is the Difference Between append() and extend() Methods in Python?

In Python, both append() and extend() are methods for adding elements to a list, but they do so in different ways:

  • append(): Adds its argument as a single element to the end of a list, increasing the length of the list by one. The argument can be any data type, and append() adds the argument as it is, as a single item.
  • extend(): Takes an iterable (e.g., another list, set, tuple) and appends each element of the iterable to the list, extending the list.

Example of append():

my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list) # Output: [1, 2, 3, [4, 5]]

Example of extend():

my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]

What is extend() in Python?

The extend() method in Python is used to add multiple elements from an iterable to the end of a list. The elements in the iterable are added individually to the list, extending it.

Usage Example:

my_list = ['a', 'b', 'c']
my_list.extend(['d', 'e', 'f']) # Adds elements of the list individually
print(my_list) # Output: ['a', 'b', 'c', 'd', 'e', 'f']

What is append() in Python?

append() in Python is used to add a single item to the end of a list. The item added by append() remains in its original form, which means that it can be of any data type.

Usage Example:

my_list = [1, 2, 3]
my_list.append(4) # Appends 4 as a single element
print(my_list) # Output: [1, 2, 3, 4]

Is extend() Faster Than append()?

When adding elements from an iterable to a list, using extend() can be faster and more direct than using append() in a loop because extend() is optimized for adding elements in bulk. However, the performance difference might not be significant for small lists or simple operations.

What is the Difference Between Append and Extend in Python argparse?

In the context of argparse, a module used for parsing command-line options, arguments, and sub-commands in Python, append and extend refer to actions for storing command-line arguments:

  • append Action: This action stores each command-line argument as a new list item. It is useful when multiple occurrences of an argument can occur, and you want to capture all of them.
  • extend Action: Introduced in Python 3.8, this action extends a list by iterating over its argument value, which is expected to be an iterable. This is particularly useful when each command-line argument is itself a list of values.

Example in argparse:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--numbers', action='append', type=int)
args = parser.parse_args()
print(args.numbers) # Output example: [1, 2, 3] if --numbers 1 --numbers 2 --numbers 3

Example in argparse:

parser.add_argument('--numbers', action='extend', type=int, nargs='+')
args = parser.parse_args()
print(args.numbers) # Output example: [1, 2, 3, 4, 5] if --numbers 1 2 3 --numbers 4 5

These differences highlight the specific uses of append and extend in both general Python programming and in specialized modules like argparse.












    Similar Reads

    Difference between Append, Extend and Insert in Python
    Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their crea
    3 min read
    Python sympy | sieve.extend() method
    With the help of sympy.sieve.extend() method, we can grow the sieve to cover all the prime numbers less than equal to a given natural number. Syntax: sieve.extend(N) Parameter: N - It denotes the number up to which the sieve is extended. Returns: The function does not return anything. Example #1: # import sympy from sympy import sieve # Use sieve.e
    1 min read
    Extend Class Method in Python
    In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism. This is similar to overriding in Java and virtual methods
    3 min read
    Python List extend() Method
    The Python List extend() method adds items of an iterable (list, tuple, dictionary, etc) at the end of a list. Example C/C++ Code other_cars = ["Maruti", "Tata"] cars.extend(other_cars) print(cars) Output ['Audi', 'BMW', 'Jaguar', 'Maruti', 'Tata']List extend() Syntaxlist_name.extend(iterable) Parameters:iterable: Any iterable (
    4 min read
    List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
    Some of the list methods are mentioned in set 1 below List Methods in Python | Set 1 (in, not in, len(), min(), max()…) More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index 'a' till 'b' mentioned in arguments. 2. pop() :- This method deletes the element at the position mentio
    4 min read
    How to Extend User Model in Django
    Django’s built-in User model is useful, but it may not always meet your requirements. Fortunately, Django provides a way to extend the User model to add additional fields and methods. In this article, we'll walk through the process of extending the User model by creating a small web project that displays a custom user profile, showcasing the popula
    3 min read
    Difference Between '+' and 'append' in Python
    Using '+' operator to add an element in the list in Python: The use of the '+' operator causes Python to access each element of that first list. When '+' is used a new list is created with space for one more element. Then all the elements from the old list must be copied to the new list and the new element is added at the end of this list. Example:
    3 min read
    Append list of dictionary and series to a existing Pandas DataFrame in Python
    In this article, we will discuss how values from a list of dictionaries or Pandas Series can be appended to an already existing pandas dataframe. For this purpose append() function of pandas, the module is sufficient. Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None) Parameters :other : DataFrame or Series/dict-
    2 min read
    Python | Pandas Index.append()
    Python is an excellent language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas are one of those packages, making importing and analyzing data much easier. Pandas Index.append() The function is used to append a single or a collection of indices together. In the case of a collection of indices,
    2 min read
    Python | Pandas TimedeltaIndex.append()
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.append() function appends a collection of index options together. More than one index object can be appended at a
    2 min read
    Python | Pandas Series.append()
    Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.append() function is used to concatenate two or more series object. Syntax: Ser
    4 min read
    Python append to a file
    While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it's opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows: Append Only (‘a’): Open the file for writing.Append and Read (‘a
    4 min read
    Python - Append content of one text file to another
    Having two file names entered by users, the task is to append the content of the second file to the content of the first file with Python. Append the content of one text file to anotherUsing file objectUsing shutil moduleUsing fileinput moduleSuppose the text files file1.txt and file2.txt contain the following data. file1.txt file2.txt Append the c
    3 min read
    Python - Append List every Nth index
    Given 2 list, append list to the original list every nth index. Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = ['G', 'F', 'G'], N = 3 Output : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8] Explanation : List is added after every 3rd element.Input : test_list = [3, 7, 8, 2, 1, 5, 8, 9], app_list = ['G', 'F', 'G'], N = 4 O
    5 min read
    How to append a list as a row to a Pandas DataFrame in Python?
    Prerequisite: Pandas DataFrame In this article, We are going to see how to append a list as a row to a pandas dataframe in Python. It can be done in three ways: Using loc[]Using iloc[]Using append()Append list using loc[] methods Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame.
    3 min read
    Future Replacement of the Append Method in Panda Python
    In The Current Version of Panda ['1.5.3'], if you use the append () function your code will get executed but In Jupyter Notebook you will receive some sort of error or can say Future Warning. Let's First execute some series code in pandas Python: Replacement of the Append Method in PandasBelow are the methods that we will cover in this article: Pro
    2 min read
    How to append elements in Python tuple?
    In this article, we will explore how to append elements to a tuple in Python. Appending elements to a tuple in Python may additionally seem counterintuitive due to the immutability of tuples. Understanding TuplesBefore we dive into appending elements to tuples, permit's quick evaluation of what tuples are and why they're beneficial. Tuples are orde
    2 min read
    Python List append() Method
    Python list append() method is used to add elements at the end of the list. Example Python Code list.append(8) print(list) Output [2, 5, 6, 7, 8] Python List Append() SyntaxList_name.append(element) Parameterelement: an element (number, string, list, etc.) to be added at the end of the list. The parameter is mandatory and omitting it can cause an e
    3 min read
    How to append new data to existing XML using Python ElementTree
    Extensible Markup Language (XML) is a widely used format for storing and transporting data. In Python, the ElementTree module provides a convenient way to work with XML data. When dealing with XML files, it is common to need to append new data to an existing XML document. This can be achieved efficiently using Python's ElementTree module. What is P
    4 min read
    numpy.append() in Python
    The numpy.append() appends values along the mentioned axis at the end of the array Syntax : numpy.append(array, values, axis = None) Parameters : array : [array_like]Input array. values : [array_like]values to be added in the arr. Values should be shaped so that arr[...,obj,...] = values. If the axis is defined values can be of any shape as it will
    3 min read
    Append to JSON file using Python
    The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
    2 min read
    Python - Pandas dataframe.append()
    Pandas append function is used to append rows of other data frames to the end of the given data frame, returning a new data frame object. Columns not in the original data frames are added as new columns and the new cells are populated with NaN value. Pandas dataframe append SyntaxSyntax: DataFrame.append(other, ignore_index=False, verify_integrity=
    5 min read
    Python | Perform append at beginning of list
    The usual append operation of a Python list adds the new element at the end of the list. But in certain situations, we need to append each element to the front of the list. If we perform brute force techniques, we need to perform unnecessary shifts of elements and hence, having shorthand for it is useful. Here, we will see how to add to a list in P
    8 min read
    Append or Concatenate Two DataFrames in Python Polars
    Polars is a fast Data Frame library implemented in Rust, providing efficient ways to work with large datasets. Whether we need to append rows or concatenate columns, Polars offers multiple methods to handle these tasks effectively. Setting Up Your EnvironmentBefore diving into the examples, ensure you have Polars installed. If not, you can install
    3 min read
    Append data to an empty Pandas DataFrame
    Let us see how to append data to an empty Pandas DataFrame. Creating the Data Frame and assigning the columns to it # importing the module import pandas as pd # creating the DataFrame of int and float a = [[1, 1.2], [2, 1.4], [3, 1.5], [4, 1.8]] t = pd.DataFrame(a, columns =["A", "B"]) # displaying the DataFrame print(t) print(t
    2 min read
    How to append a new row to an existing csv file?
    For writing a CSV file, the CSV module provides two different classes writer and Dictwriter. Here we will discuss 2 ways to perform this task effectively. The First will be 'append a list as a new row to the existing CSV file' and second way is 'Append a dictionary as a new row to the existing CSV file.' First, let's have a look at our existing CSV
    3 min read
    How to append two NumPy Arrays?
    Prerequisites: Numpy Two arrays in python can be appended in multiple ways and all possible ones are discussed below. Method 1: Using append() method This method is used to Append values to the end of an array. Syntax : numpy.append(array, values, axis = None) Parameters : array: [array_like]Input array.values : [array_like]values to be added in th
    4 min read
    BeautifulSoup - Append to the contents of tag
    Prerequisites: Beautifulsoup Beautifulsoup is a Python library used to extract the contents from the webpages. It is used in extracting the contents from HTML and XML structures. To use this library, we need to install it first. Here we are going to append the text to the existing contents of tag. We will do this with the help of the BeautifulSoup
    2 min read
    How to Fix: ‘numpy.ndarray’ object has no attribute ‘append’
    NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. If you are into analytics, you might have come across this library in python. In the beginning, some things might confuse a programmer
    4 min read
    Append data to an empty dataframe in PySpark
    In this article, we are going to see how to append data to an empty DataFrame in PySpark in the Python programming language. Method 1: Make an empty DataFrame and make a union with a non-empty DataFrame with the same schema The union() function is the most important for this operation. It is used to mix two DataFrames that have an equivalent schema
    5 min read
    Practice Tags :
    three90RightbarBannerImg