Lists are one of the best data structures to use. Storing and extracting values from the list is a breeze. Python has many concepts and functions that work on the lists to maintain, update, and retrieve data.
Python list insert
The list insert() is a built-in Python function that inserts an element to the list at the given index. The insert() method accepts index and element as arguments and does not return any value, but it inserts the given element at the given index.
The syntax for the insert() method is the following.
Syntax
list.insert(index, element)
Parameters
The insert() function takes two parameters:
- index – It is a required parameter and a position where an element needs to be inserted.
- element – It is a required parameter, which 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
Inserting the Tuple as an Element to the List
To insert a tuple in List in Python, use the list.insert() method. 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 starts from 0. Let us see the output.
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
To insert a Set as an element in Python, use the list.insert() method. 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)
That’s it for this tutorial.