I want to insert an element at a specific index in a list and return the updated list.

0 votes

Here is my list:

a = [2, 5, 7, 8, 9]

And I want to insert 3 and 4 after 5 ( at index 2 and 3 repectively)

Jun 7 in Python by Shabnam
• 400 points

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes


Using insert() method you can insert the elements in given list at required index.


list_name.insert(index, element)

Now coming to your code:

a = [2, 5, 7, 8, 9]

#element to be inserted

Element = 3 

#element to be inserted before

beforeElement = 7

#find index

index = a.index(beforeElement)  

#insert element at beforeElement 

a.insert(index, Element)  

#Similarly to insert 4 after 3 in the list:

Element = 4
index= a.index(beforeElement)
a.insert(index, Element)


[2, 5, 3, 4, 7, 8, 9]

As asked above, we have 3 and 4 after 5 in the list as output

answered Jun 7 by Taj
• 560 points

Related Questions In Python

0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,710 points
+7 votes
2 answers

I want to build a recommender system incorporating diversity and accuracy in the recommender engine.

I dont know what exactly you are ...READ MORE

answered Sep 24, 2018 in Python by slayer
• 29,040 points
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,710 points
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
0 votes
1 answer

In Python, what is difference between Array and List?

Lists and arrays are used in Python ...READ MORE

answered Mar 15 in Python by Taj
• 560 points

edited Mar 18 by Omkar 281 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.