python

Python – How to Insert an element at a specific index in List

In this tutorial, we are going to see how to insert an element at a specific index in List in Python.
 

Insert an element at a specific index in List
# String List
list1 = ['Python', 'Java', 'C', 'C++', 'PHP']
# Add an item to the 3rd position in the list
list1.insert(2, 'Ruby')
# print the list
print(list1)

Output:

['Python', 'Java', 'Ruby', 'C', 'C++', 'PHP']
 

Add an element at the begining of the list
# String List
list1 = ['Python', 'Java', 'C', 'C++', 'PHP']
# Add an element at the begining of the list
list1.insert(0, 'Pascal')
# print the list
print(list1)

Output:

['Pascal', 'Python', 'Java', 'C', 'C++', 'PHP']

 

Insert all elements from another list to a specific index in a given list
# String List
list1 = ['Python', 'Java', 'C', 'C++', 'PHP']
list2 = ['blue', 'green', 'red']
# Add all the elements of list2 in list1 between the 2nd and the 3rd element
for item in reversed(list2) :
    list1.insert(2, item)
# print the list
print(list1)

Output:

['Python', 'Java', 'blue', 'green', 'red', 'C', 'C++', 'PHP']
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *