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, 2019 in Python by Shabnam
• 930 points
1,933 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, 2019 by Taj
• 1,080 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
2,343 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,370 points
2,123 views
+1 vote
4 answers

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

Delete the List and its element: We have ...READ MORE

answered Jun 7, 2020 in Python by sahil
• 500 points
280,742 views
0 votes
1 answer

I want to download a file from the website by web scraping. Can anyone explain how to do this in jupyter lab (python) with an example?

Hey, Web scraping is a technique to automatically ...READ MORE

answered Apr 7, 2020 in Python by Gitika
• 65,770 points
2,392 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,441 views
0 votes
1 answer
+1 vote
4 answers

In Python, what is difference between Array and List?

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

answered Mar 15, 2019 in Python by Taj
• 1,080 points

edited Mar 18, 2019 by Omkar 152,798 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP