Which function in list is used to insert item at the given position?

Python List insert[]

In this tutorial, we will learn about the Python List insert[] method with the help of examples.

The insert[] method inserts an element to the list at the specified index.

Example

# create a list of vowels vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 [4th position] vowel.insert[3, 'o']
print['List:', vowel] # Output: List: ['a', 'e', 'i', 'o', 'u']

Python List insert[]

The Python List insert[] method is an inbuilt function in Python that inserts a given element at a given index in a list.

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.

Returns:



This method does not return any value but it inserts the given element at the given index.

Error:

If anything other than a list is used with insert[], then it returns an AttributeError.

Note:

If given index >= length[list] is given, then it inserts at the end of the list.

Example1: Inserting an Element to the List

Python3




# Python3 program for use
# of insert[] method
list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
# insert 10 at 4th index
list1.insert[4, 10]
print[list1]
list2 = ['a', 'b', 'c', 'd', 'e']
# insert z at the front of the list
list2.insert[0, 'z']
print[list2]

Output:

[1, 2, 3, 4, 10, 5, 6, 7] ['z', 'a', 'b', 'c', 'd', 'e']

Example 2: Error of insert[] Method

Python3




# Python3 program for error
# of insert[] method
# 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'

Example 3: Insertion in a List Before any Element

Python3




# 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]

Example 4: Inserting a Tuple to the List

Python3




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]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python-Built-in-functions
python-list
python-list-functions
Practice Tags :
python-list
Read Full Article

Inserting an element in list at specific index using list.insert[]

In python list provides a member function insert[] i.e.

list.insert[position, element]
It accepts a position and an element and inserts the element at given position in the list.

Let’s see an example,

Suppose we have a list of strings i.e.

# List of string list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
Now let insert ‘why’ at 3rd position in the list i.e.
# Add an element at 3rd position in the list list1.insert[3, 'why']
Index will start from 0 in list. So, element will be inserted at 3rd position i.e. after 0,1 & 2.
Advertisements

So, list contents will be now,

['Hi', 'hello', 'at', 'why', 'this', 'there', 'from']

Python – Insert Item at Specific Index in List

To insert or add an item at specific position or index in a list, you can use insert[] method of List class.

In this tutorial, we shall learn how to insert an item in a list, at given position, with the help of example Python programs.

Syntax – insert[]

The syntax of insert[] method is:

mylist.insert[index, item]

The items present from the specified index are shifted right and specified item is inserted at the index.

Example 1: Insert Item at Specified Index in List

In the following example, we have list of numbers. We will insert an item 36, in the list at index 4.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 36 index = 4 #insert item in mylist at index mylist.insert[index, item] print[mylist]Run

Output

[21, 5, 8, 52, 36, 21, 87, 52]

Example 2: Insert Item at Start of List

In the following example, we will insert 36, at the start of the list. To insert at start, we need to provide the index as 0 to insert[] method.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 36 index = 0 #1st position #insert item in mylist at index mylist.insert[index, item] print[mylist]Run

Output

[36, 21, 5, 8, 52, 21, 87, 52]

Example 3: Insert Item at End of List

We will insert an item at end of the list. To insert item at the end, provide index, as length of the list, to insert[] method.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 36 index = len[mylist] #insert item in mylist at index mylist.insert[index, item] print[mylist]Run

Output

[21, 5, 8, 52, 21, 87, 52, 36]

Example 4: Insert Item with Index out of Bounds of List

If the index provided to insert[] method is more than the length of the list, it just appends the item to the list.

Here in this example, the index provided is way out of bounds and more than the length of the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 36 index = 1000 #index out of bounds of list #insert item in mylist at index mylist.insert[index, item] print[mylist]Run

Output

[21, 5, 8, 52, 21, 87, 52, 36]

If you provide a negative index, the item is inserted at the beginning of the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 36 index = -10 #index out of bounds of list #insert item in mylist at index mylist.insert[index, item] print[mylist]Run

Output

[36, 21, 5, 8, 52, 21, 87, 52]

Summary

In this tutorial of Python Examples, we learned how to insert an item at given position in the list.

Related Tutorials

  • Python Program to Find Smallest Number in List
  • Python – Check if Element is in List
  • How to Reverse Python List?
  • Python Program to Find Duplicate Items of a List
  • Python List of Dictionaries
  • Python List without Last Element
  • Python List – Add Item
  • Python List of Lists
  • Python – Get Index or Position of Item in List
  • How to Get List of all Files in Directory and Sub-directories?

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4] >>> insert_at = 2 # Index at which you want to insert item >>> b = a[:] # Created copy of list "a" as "b". # Skip this step if you are ok with modifying the original list >>> b[insert_at:insert_at] = [3] # Insert "3" within "b" >>> b [1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4] >>> insert_at = 2 # Index starting from which multiple elements will be inserted # List of elements that you want to insert together at "index_at" [above] position >>> insert_elements = [3, 5, 6] >>> a[insert_at:insert_at] = insert_elements >>> a # [3, 5, 6] are inserted together in `a` starting at index "2" [1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index[...] is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.

Alternative using list comprehension [but very slow in terms of performance]:

As an alternative, it can be achieved using list comprehension with enumerate too. [But please don't do it this way. It is just for illustration]:

>>> a = [1, 2, 4] >>> insert_at = 2 >>> b = [y for i, x in enumerate[a] for y in [[3, x] if i == insert_at else [x, ]]] >>> b [1, 2, 3, 4]

Python List Insert

Contents

  • 1 List Insert Method
  • 2 How does the Insert[] function work?
  • 3 Program Examples
    • 3.1 Insert a string in the list
    • 3.2 Insert a tuple in the list
    • 3.3 List after using the wrong index

To Learn about Lists – Read Python List

List Insert Method

The Insert function is a built-in list method that allows you to insert items or objects at any position in a sequence. It’s a list-only method.

Its syntax is as follows:

List_name.insert[index, element]

The arguments are “index” and “element” where index is the position of the item needs to get inserted, and the “element” is the element given by the user.

The insert method returns nothing, i.e., it has no return value. See the below example.

>>> myList = [1, 9, 16, 25] >>> myList.insert[1, 4] >>> print[myList] [1, 4, 9, 16, 25] >>>

In the above example code, you can observe that we have a list containing the sequence of squares of natural numbers from 1 to 5. Here the “4” was missing. To remedy this, we inserted it at 1st index in the list.

How does the Insert[] function work?

When the user calls the insert method and passes the index, the function first checks its existence in the list.

If it exists, then the element gets inserted at the given position in the list. After that, it also updates the indexes of the rest of the items.

The following flowchart simplifies it for you:

Program Examples

We can insert different data types in a list. Examples include a list, tuple, strings, etc.

Insert a string in the list

List = [1,2,3] List.insert[0, "Insert"] print[List]

The output is as follows:

['Insert', 1, 2, 3]

Insert a tuple in the list

List = [1, 2, 3] List.insert[1, [6, 5]] print[List]

The result is as follows:

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

List after using the wrong index

List = [1,2,3] List.insert[5,"Insert"] print [List] List.insert[-4, "Beginning"] print [List]

The output is as follows:

[1, 2, 3, 'Insert'] ['Beginning', 1, 2, 3, 'Insert']

Even when use out of range index values, the insert method will still insert at the ends of the list.

Best,

TechBeamers

Usage

Useinsert[]method to insert a single item at a specified index in a list. Note that other items are shifted to the right.

This method does not return anything; it modifies the list in place.

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề