The Wayback Machine - http://web.archive.org/web/20240828001306/https://www.geeksforgeeks.org/difference-between-append-extend-and-insert-in-python/
Open In App

Difference between Append, Extend and Insert in Python

Last Updated : 05 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 creation. Lists have various methods, the most commonly used list method are append(), insert(), extend(), etc. In this article, we are going to discuss the difference between append(), insert(), and, extend() method in Python lists.

Append

It adds an element at the end of the list. The argument passed in the append function is added as a single element at end of the list and the length of the list is increased by 1.

Syntax:

list_name.append(element)

The element can be a string, integer, tuple, or another list.

Example:

Python3




# python program to demonstrate
# working of append function
 
# assign list
l = ['geeks']
 
# use method
l.append('for')
l.append('geeks')
 
# display list
print(l)


Output:

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

Insert

This method can be used to insert a value at any desired position. It takes two arguments-element and the index at which the element has to be inserted.

Syntax:

list_name(index,element)

The element can be a string, object, or integer.

Example:

Python3




# python program to demonstrate
# working of insert function
 
# assign list
l = ['geeks', 'geeks']
 
# use method
l.insert(1, 'for')
 
# display list
print(l)


Output:

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

Extend

This method appends each element of the iterable (tuple, string, or list) to the end of the list and increases the length of the list by the number of elements of the iterable passed as an argument.

Syntax:

list_name.extend(iterable)

Example:

Python3




# python program to demonstrate
# working of extend function
 
# assign list
l = ['hello', 'welcome', 'to']
 
# use method
l.extend(['geeks', 'for', 'geeks'])
 
# display list
print(l)


Output:

['hello', 'welcome', 'to', 'geeks', 'for', 'geeks']

Difference between Append, Extend and Insert

append() insert() extend()
The element passed as an argument is appended to the end of the list The element passed as the argument can be inserted at any desired position by passing the index along with it as a parameter. Each element of the iterable passed as an argument gets appended to the end of the list.
An iterable passed as an argument appends without any change as a single element to the end of the list. An iterable passed as an argument appends without any change as a single element to the desired index of the list. An iterable passed as an argument will append each of its elements to the end of the list
Length of the list increases by 1 Length of the list increases by 1 Length of the list increases by the number of elements in the iterable.
Has a constant time complexity of O(1) Has a linear complexity of O(n). Has a time complexity of O(k) where k is the length of the iterable.

Comparing the methods in a single program:

Python3




# Python program to demonstrate
# comparison between the three methods
 
# assign lists
list_1 = [1, 2, 3]
list_2 = [1, 2, 3]
list_3 = [1, 2, 3]
 
a = [2, 3]
 
# use methods
list_1.append(a)
list_2.insert(3, a)
list_3.extend(a)
 
# display lists
print(list_1)
print(list_2)
print(list_3)


Output:

[1, 2, 3, [2, 3]]
[1, 2, 3, [2, 3]]
[1, 2, 3, 2, 3]


Similar Reads

append() and extend() in Python
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 behavi
6 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
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
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
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 insert(), insertOne(), and insertMany() in Pymongo
MongoDB is a NoSql Database that can be used to store data required by different applications. Python can be used to access MongoDB databases. Python requires a driver to access the databases. PyMongo enables interacting with MongoDB database from Python applications. The pymongo package acts as a native Python driver for MongoDB. Pymongo provides
4 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