AppDividend
Latest Code Tutorials

Python List Insert Example | insert() Method Tutorial

0

Python List Insert Example | insert() Method Tutorial is today’s topic. Lists are one of the best data structures to use. Storing and extracting values from it is a breeze. Python has a vast number of concepts and functions that work on the lists to maintain, update and retrieve data. The list insert() method inserts an item to the list at the given index. Python list insert() method does not return any value, but it inserts the given element at the given index.

Python List Insert Example

The syntax for insert() method is following.

list.insert(index, element)

The insert() function takes two parameters:

  • index – It is a required parameter, and it is a position where an element needs to be inserted.
  • element – It is a required parameter, and this is the element to be inserted in the list.

Let us take a simple example.

# app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
GoT.insert(1, 'Varys')
print(GoT)

Run the file. My Python version is 3.6.4.

python3 app.py

 

Python List Insert Example | insert() Method Tutorial

Inserting the Tuple as an Element to the List

We can also add a Tuple as an element to the specified position.

app.py

GoT1_list = ['Daenerys', 'Jon', 'Tyrion']
Friends1_tuple = ('Rachel', 'Monica', 'Phoebe')
GoT1_list.insert(2, Friends1_tuple)
print(GoT1_list)

So, here we are adding one tuple at the position index 2. In Python, the list index is starting from 0. Let us see the output.

 

Inserting a Tuple as an Element to the List

So, it inserts an item at a given position. The first argument is the index of the element before which to insert, so a list.insert(index, element) inserts at the front of the list.

Inserting a Set as an Element to the List

We can also add a set in the list in a specified position.

// app.py

GoT1_list = ['Daenerys', 'Jon', 'Tyrion']
Friends1_set = {'Rachel', 'Monica', 'Phoebe'}
GoT1_list.insert(2, Friends1_set)
print(GoT1_list)

 

Inserting a Set as an Element to the List

Finally, Python List Insert Example | insert() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

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