Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this?

For example, suppose my list has the following integers

>>> a = [1,2,3,4,5,1,2,3,4,5,1]

and I need to replace all occurrences of the number 1 with the value 10 so the output I need is

>>> a = [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

Thus my goal is to replace all instances of the number 1 with the number 10.

1 Answer

0 votes
by (106k points)

For finding and replacing elements in a list you can use the below-mentioned code:-

>>> a= [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1] 

>>> for n, i in enumerate(a): 

... if i == 1: 

... a[n] = 10 

... 

>>> a 

[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Oct 3, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...