The Wayback Machine - https://web.archive.org/web/20240912015353/https://www.geeksforgeeks.org/python-list-insert/
Open In App

Python List insert() Method With Examples

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

Python List insert() method inserts an item at a specific index in a list.

Example:

Python
# creating a list
fruit = ["banana","cherry","grape"]
fruit.insert(1,"apple")
print(fruit)

Output
['banana', 'apple', 'cherry', 'grape']

Definition and Use of List insert() Method

List insert() method in Python is very useful to insert an element in a list. What makes it different from append() is that the list insert() function can add the value at any position in a list, whereas the append function is limited to adding values at the end.

It is used in editing lists with huge amount of data, as inserting any missed value in that list is made very easy with this Python function.

List insert() Method Syntax

list_name.insert(index, element)

Parameters:

  • index: the index at which the element has to be inserted.
  • element: the element to be inserted in the list.

Return : The insert() method returns None. It only updates the current list.

How to Insert into Python List at Index?

Using Python list insert() function you can easily insert an item to a given index in Python list.

Example

Python
# making a list
score = [43,45,99,76]
#inserting a new score at third position
score.insert(2, 45)
#printing new list
print(score)

Output
[43, 45, 45, 99, 76]

More Examples on Python List insert() Method

Here is another examples to depict Python list insert at index 0:

Python
list = ['Sun', 'rises', 'in', 'the', 'east']
list.insert(0, "The")
print(list)

Output
['The', 'Sun', 'rises', 'in', 'the', 'east']

Let’s see some of the scenarios with the python list insert() function to clearly understand the workings of the insert() function.

1. Inserting an Element to a specific index into the List

Here, we are inserting 10 at the 5th position (4th index) in a Python list.

Python
list1 = [ 1, 2, 3, 4, 5, 6, 7 ] 

# insert 10 at 4th index 
list1.insert(4, 10) 
print(list1) 

Output
[1, 2, 3, 4, 10, 5, 6, 7]

2. Error of insert() Method

Here, we are inserting 1 at the 10th position in a Python list, we will get an error if we try to insert anything in a string because the string doesn’t have attribute insert().

Python
# attribute error
string = "1234567"

string.insert(10, 1)
print(string)

Output: 

Traceback (most recent call last):
File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
line 7, in
string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'


3. Insertion in a List Before any Element

In the parse of Python List Insert here, we are inserting 13 at the 3rd position before 3 in a Python list.

Python
# Python3 program for Insertion in a list  
# before any element using insert() method 

list1 = [ 1, 2, 3, 4, 5, 6 ]

# Element to be inserted 
element = 13 

# Element to be inserted before 3
beforeElement = 3 

# Find index
index = list1.index(beforeElement) 

# Insert element at beforeElement 
list1.insert(index, element) 
print(list1)

Output
[1, 2, 13, 3, 4, 5, 6]

4. Inserting a Tuple into the List

Here we are inserting a tuple in a list using the insert() function in Python.

Python
list1 = [ 1, 2, 3, 4, 5, 6 ]

# tuple of numbers
num_tuple = (4, 5, 6)

# inserting a tuple to the list
list1.insert(2, num_tuple)

print(list1)

Output
[1, 2, (4, 5, 6), 3, 4, 5, 6]

5. Insert an Element to the Beginning of a List 

In this example, we are inserting the “orange” string at the 0 index of the fruits list.

Python
fruits = ['apple', 'banana', 'cherry']
fruits.insert(0, 'orange')
print(fruits)
 # Output: ['orange', 'apple', 'banana', 'cherry']

Output
['orange', 'apple', 'banana', 'cherry']

6. Inserting an Element at the end of the List

In this example, we are inserting the “cherry” at the end of the list.

Python
fruits = ['apple', 'banana', 'cherry']
fruits.insert(-1, 'orange')
print(fruits) 
# Output: ['apple', 'banana', 'orange', 'cherry']

Output
['apple', 'banana', 'orange', 'cherry']

7. Inserting a dictionary to a list in Python

Here we are inserting a dictionary in a list using the insert() function in Python.

Python
my_list = [{'name': 'Alice', 'age': 30}, 
           {'name': 'Bob', 'age': 25}]
new_dict = {'name': 'Charlie', 'age': 40}

my_list.append(new_dict)

print(my_list)

Output
[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 40}]

8. Python Insert List in Another List

Here we are inserting a list in a list using the insert() function in Python.

Python
list1 = [1, 2, 3]
list2 = [4, 5, 6]

list1=list1+list2

print(list1)

Output
[1, 2, 3, 4, 5, 6]

9. Insert elements of a set to a list in Python

Here we are inserting a set in a list using the insert() function in Python.

Python
list1 = [1, 2, 3]
s= {4,5,6}

list1.insert(3,s)

print(list1)

Output
[1, 2, 3, {4, 5, 6}]

Go to the below articles to get more details information about Python Insert() Function

In the above article, we have discussed the Python list insert() method and its parameters with suitable examples. Python insert() function is very useful when dealing with big data.

We hope this article taught you about how to use insert() in Python.

Python List insert() Method With Examples – FAQS


What is the insert() Method in Python?

The insert() method in Python allows you to add an element to a specific position within a list. It takes two arguments: the index where the element should be inserted and the element itself.

What is the Difference Between insert() and append() Methods of a List?

  • insert() method adds an element at a specified index.
  • append() method adds an element to the end of the list, effectively equivalent to list.insert(len(list), element).

What is the Use of append() Function in List?

The append() function is used to add a single element to the end of a list. It does not return a new list; instead, it modifies the original list.

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

  • append() adds its argument as a single element to the end of a list.
  • extend() takes an iterable as an argument and appends each of its elements to the list, effectively flattening the input iterable one level.

What is items() Method in Python?

The items() method in Python is used with dictionaries to return a view object that displays a list of dictionary’s key-value tuple pairs. For example, dict.items() allows you to loop through both keys and values in a dictionary simultaneously.



Previous Article
Next Article

Similar Reads

Python | Insert the string at the beginning of all items in a list
Given a list, write a Python program to insert some string at the beginning of all items in that list. Examples: Input : list = [1, 2, 3, 4], str = 'Geek' Output : list = ['Geek1', 'Geek2', 'Geek3', 'Geek4']Input : list = ['A', 'B', 'C'], str = 'Team' Output : list = ['TeamA', 'TeamB', 'TeamC'] There are multiple ways to insert the string at the be
3 min read
Python | Split given list and insert in excel file
Given a list containing Names and Addresses consecutively, the task is to split these two elements at a time and insert it into excel. We can use a very popular library for data analysis, Pandas. Using pandas we can easily manipulate the columns and simply insert the filtered elements into excel file using df.to_excel() function. Below is the imple
1 min read
Python | Insert Nth element to Kth element in other list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed. Method 1: Using pop() + insert() + index() This particular task can be performed using a combinat
9 min read
Insert Python list into PostgreSQL database
In this article, we will discuss how to Insert a Python list into PostgreSQL database using pyscopg2 module. Psycopg2 is the most popular PostgreSQL adapter for the Python programming language. Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-threaded applications and manages its own connecti
2 min read
Insert and delete at the beginning in Doubly Linked List in Python
A doubly linked list is a collection of nodes. It is an advanced version of a singly linked list. In a doubly linked list, a node has three elements its data, a link to the next node, and a link to its previous node. In this article, we will learn how to insert a node at the beginning and delete a node from the beginning of the doubly linked list.
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
Python | Pandas Index.insert()
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 Index.insert() function make new Index inserting new item at location. This function also follows Python list.append() semantics
2 min read
Python SQLite - Insert Data
In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to b
3 min read
MongoDB Python | Insert and Update Data
Prerequisites : MongoDB Python Basics We would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection. Insert data We would
3 min read
MongoDB Python - Insert and Replace Operations
This article focus on how to replace document or entry inside a collection. We can only replace the data already inserted in the database. Prerequisites : MongoDB Python Basics Method used: replace_one() Aim: Replace entire data of old document with a new document Insertion In MongoDB We would first insert data in MongoDB. C/C++ Code # Python code
3 min read
Python | Pandas TimedeltaIndex.insert
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.insert() function return the underlying data as an ndarray of the given TimedeltaIndex object. Syntax : TimedeltaI
2 min read
Python MySQL - Insert into Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. Note: Before we insert data into
3 min read
PostgreSQL - Insert Data Into a Table using Python
In this article we will look into the process of inserting data into a PostgreSQL Table using Python. To do so follow the below steps: Step 1: Connect to the PostgreSQL database using the connect() method of psycopg2 module.conn = psycopg2.connect(dsn) Step 2: Create a new cursor object by making a call to the cursor() methodcur = conn.cursor() Ste
2 min read
Python MariaDB - Insert into Table using PyMySQL
MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article we will look into the process of inserting rows to a table of the database using pymysql. You can insert one row or multiple rows at once. The connector cod
2 min read
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
Get the id after INSERT into MySQL database using Python
Prerequisites: MySQL, mysql-connector for python The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to M
2 min read
How to randomly insert NaN in a matrix with NumPy in Python ?
Prerequisites: Numpy In this article, let's see how to generate a Python Script that randomly inserts Nan into a matrix using Numpy. Given below are 3 methods to do the same: Method 1: Using ravel() function ravel() function returns contiguous flattened array(1D array with all the input-array elements and with the same type as it). A copy is made o
3 min read
How to insert values into MySQL server table using Python?
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicatin
2 min read
How to Insert Image in SQLite using Python?
In this article, we will discuss how to insert images in SQLite using sqlite3 module in Python. Implementation: 1. Set the connection to the SQLite database using Python code. sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db') cursor = sqliteConnection.cursor() 2. We need to define an INSERT query for inserting the BLOB data into the t
2 min read
Insert Python Dictionary in PostgreSQL using Psycopg2
In this article, we are going to see how to insert a Python dictionary in PostgreSQL using Psycopg2. We can insert a python dictionary by taking the dictionary keys as column names and values as dictionary values. We import the Psycopg2 package and form a connection to the PostgreSQL database using psycopg2.connect() method. First, let's create a t
2 min read
Python Psycopg2 - Insert multiple rows with one query
This article is about inserting multiple rows in our table of a specified database with one query. There are multiple ways of executing this task, let's see how we can do it from the below approaches. Method 1: Inserting Values through Naive method In this method, we import the psycopg2 package and form a connection using the psycopg2.connect() met
4 min read
How to insert current_timestamp into Postgres via Python?
For processing timestamps, PostgreSQL supports two data types timestamp and timestamptz. timestamp datatype helps us create a timestamp without timezone, and timestamptz helps us create a timestamp with a timezone. One may store both date and time with the timestamp datatype. It does not, however, include time zone information. It implies that if y
2 min read
Bulk Insert to Pandas DataFrame Using SQLAlchemy - Python
Let's start with SQLAlchemy, a Python library that allows communication with databases(MySQL, PostgreSQL etc.) and Python. This library is used as an Object Relational Mapper tool that translates Python classes to tables in relational databases and automatically converts function calls to SQL statements that gives application developers the full po
3 min read
Bulk insert with SQLAlchemy ORM in Python
In this article, we will see how to insert or add bulk data using SQLAlchemy in Python. SQLAlchemy is among one of the best libraries to establish communication between python and databases. We have used the PostgreSQL database for this article. Create a database for demonstration: CREATE DATABASE TEST; Create a connection to the Postgres database
1 min read
Python MySQL - Insert record if not exists in table
In this article, we will try to insert records and check if they EXISTS or not. The EXISTS condition in SQL is used to check if the result of a correlated nested query is empty (contains no tuples) or not. It can be used to INSERT, SELECT, UPDATE, or DELETE statements. Pre-requisite Connect MySQL Database to PythonPythonInsert Record If Not Exists
4 min read
Python | Pandas dataframe.insert()
Pandas insert method allows the user to insert a column in a data frame or series(1-D Data frame). A column can also be inserted manually in a data frame by the following method, but there isn't much freedom here. For example, even column location can't be decided and hence the inserted column is always inserted in the last position in Python. Pand
8 min read
numpy.insert() in Python
The numpy.insert() function inserts values along the mentioned axis before the given indices. Syntax : numpy.insert(array, object, values, axis = None) Parameters : array : [array_like]Input array. object : [int, array of ints]Sub-array with the index or indices before which values is inserted values : [array_like]values to be added in the arr. Val
4 min read
Insert Multiple Rows in MySQL Table in Python
MySQL is an open-source, Relational Database Management System (RDBMS) that stores data in a structured format using rows and columns. It is software that enables users to create, manage, and manipulate databases. So this is used in various applications across a wide range of industries and domains. To run the MySQL server in our systems we need to
5 min read
Perform Insert Operations with psycopg2 in Python
psycopg2 is a widely used Python library designed to facilitate communication with PostgreSQL databases, offering a robust and efficient way to perform various database operations. It is a powerful and flexible connector, which allows Python applications to execute SQL commands and handle data seamlessly. Insert operation is one of the core operati
10 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read