Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add the element in a Python list with help of indexing
A Python list is a collection data type that is ordered and changeable. It allows duplicate members and is the most frequently used collection data type in Python programs. We can add elements to a list at specific positions using indexing and the insert() method.
Before adding elements, let's first understand how to access list elements using indexing.
Accessing List Elements Using Index
Every element in a list is associated with an index, which keeps the elements ordered. We can access elements by their index positions using slicing or direct indexing ?
vowels_list = ['a', 'i', 'o', 'u']
print("Element at index 1:", vowels_list[1])
print("Elements from index 1 to 3:", vowels_list[1:3])
Element at index 1: i Elements from index 1 to 3: ['i', 'o']
Adding Element at Specific Index
The insert() method allows us to add an element at a particular index position. All elements after the specified index shift to the right ?
Syntax
list.insert(index, element)
Example
vowels = ['a', 'i', 'o', 'u']
print("Original list:", vowels)
# Insert 'e' at index 1
vowels.insert(1, 'e')
print("After inserting 'e' at index 1:", vowels)
Original list: ['a', 'i', 'o', 'u'] After inserting 'e' at index 1: ['a', 'e', 'i', 'o', 'u']
Multiple Insertions
You can insert multiple elements at different positions by calling insert() multiple times ?
numbers = [1, 3, 5]
print("Original list:", numbers)
# Insert elements at different positions
numbers.insert(1, 2) # Insert 2 at index 1
numbers.insert(3, 4) # Insert 4 at index 3
print("After multiple insertions:", numbers)
Original list: [1, 3, 5] After multiple insertions: [1, 2, 3, 4, 5]
Key Points
- The
insert()method takes two parameters: index position and element to insert - Elements after the insertion point automatically shift to the right
- If the index is greater than the list length, the element is added at the end
- Negative indices can also be used for insertion
Conclusion
Use the insert(index, element) method to add elements at specific positions in a Python list. This method shifts existing elements to maintain the list's order and allows precise control over element placement.
