Table of Contents
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']
1. Syntax of List insert()
The syntax of the insert() method is
list.insert(i, elem)
Here, elem is inserted to the list at the ith index. All the elements after elem are shifted to the right.
2. insert() Parameters
The insert() method takes two parameters:
- index – the index where the element needs to be inserted
- element – this is the element to be inserted in the list
Notes:
- If index is 0, the element is inserted at the beginning of the list.
- If index is 3, the index of the inserted element will be 3 (4th element in the list).
3. Return Value from insert()
The insert() method doesn’t return anything; returns None. It only updates the current list.
4. Example 1: Inserting an Element to the List
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# insert 11 at index 4
prime_numbers.insert(4, 11)
print('List:', prime_numbers)
Output
List: [2, 3, 5, 7, 11]
5. Example 2: Inserting a Tuple (as an Element) to the List
mixed_list = [{1, 2}, [5, 6, 7]]
# number tuple
number_tuple = (3, 4)
# inserting a tuple to the list
mixed_list.insert(1, number_tuple)
print('Updated List:', mixed_list)
Output
Updated List: [{1, 2}, (3, 4), [5, 6, 7]]
Related posts:
Python Function Arguments
Python Program to Find the Size (Resolution) of a Image
Python Program to Display Fibonacci Sequence Using Recursion
Machine Learning with Python for everyone - Mark E.Fenner
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Find the Factorial of a Number
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
APIs in Node.js vs Python - A Comparison
Python Statement, Indentation and Comments
Python Modules
Python str()
Python Program to Get the File Name From the File Path
Python strptime()
Finding Max/Min of a List or Collection
Python range()
Python String rsplit()
Python String rfind()
Python dir()
Python reversed()
Python list()
Using a List of Values in a JdbcTemplate IN Clause
Converting Between a List and a Set in Java
Python Set symmetric_difference_update()
Python frozenset()
How to get current date and time in Python?
Python Program to Count the Occurrence of an Item in a List
Removing all Nulls from a List in Java
Python Program to Reverse a Number
Python Shallow Copy and Deep Copy
Python Tuple count()
Python Program to Find All File with .txt Extension Present Inside a Directory