From this , you will be learning about . You will see how to use it on sequences with the help of .

Note: The syntax used in the below section is for Python 3. You can change it to any other versions of Python.

Python List Insert

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:

Python List Insert Method flowchart  - Python List Insert Method flowchart - Python List Insert Method Explained with Examples

Program Examples

We can insert different 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")

The output is as follows:

['Insert', 1, 2, 3]

Insert a tuple in the list

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

The result is as follows:

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

List after using the wrong index

List = [1,2,3]
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.



Source link


Please enter your comment!
Please enter your name here