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
• 920 points
33 views

1 answer to this question.

0 votes

Hi,

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

Syntax:

list_name.insert(index, element)

Now coming to your code:

Input:
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)  
print(a)

#Similarly to insert 4 after 3 in the list:

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

Output:

[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
• 1,040 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,720 points
98 views
+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,170 points
178 views
0 votes
1 answer

How do I remove an element from a list by index in Python?

You can use the pop() method to ...READ MORE

answered Jun 21 in Python by Nisa
• 1,090 points
276 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 349 views
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
• 1,040 points

edited Mar 18 by Omkar 6,193 views