Python list insert Function | at End, Front, List into List Examples

Python list insert function is used to insert (add) elements in List. insert() is an inbuilt function in Python.

With insert() method you can inserts the specified value at the specified position.

Syntax

Parameters

  • index – where an element needs to be inserted. (Required)
  • element – this is the element to be inserted in the list. (Required)

Return value

It doesn’t return anything.

Example of Python list insert() Function

1. Inserting Element to List

In the below example we are adding a number 7 at position 0;

Output:

New List: [7, 1, 2, 3, 4, 5, 6]

2. insert at “End”

Let’s see how to insert a elements at end in the Python list.

In the insert method use len() function at index value.

Example code:

Output:

New List: [1, 2, 3, 4, 5, 6, 7]

Note: If given index >= length(list) is given, then it inserts at the end of the list.

3. insert at “Front”

You can insert a element in the python list insert at front using below code:-

Just use index value 0 –

Output:

New List: [‘First’, ‘a’, ‘b’, ‘c’, ‘d’]

What is the Python list insert complexity?

According to Python’s official Time Complexity page1, using list.insert always has O(n) (linear) complexity.

TypeError: insert() function

According to the documentation, the insert method takes 2 positional (ordering matters) arguments. If you miss anyone will get an error.

Output:

TypeError: insert() takes exactly 2 arguments (1 given)

Python list insert Function example

Q: How to remove elements from the list in Python?

Answer: Use python remove() function to remove or delete elements from a list.

Read this tutorial for complete example and codes – Python list remove() function

Q: Is it possible to insert a List into List in Python?

Answer: Yes you can Insert list in another list. A insert() method, can insert one element by 1 at a time.

You can’t do it like that:-

Output:

List 1 : [4, 5, 6, 3, 9]
The list 1 after insertion: [2, 3, 4, 5, 6, 3, 9]

Q: Can you Insert a Tuple (as an Element) to the List

Answer: Yes, you can insert a tuple as an element into the list.

Output:

New List: [(3, 4), ‘a’, ‘b’, ‘c’]

Do comment if you have any doubts and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code is in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.