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?<
You can simply use list comprehension in python:
def replace_element(YOUR_LIST, set_to=NEW_VALUE):
return [i
if SOME_CONDITION
else NEW_VALUE
for i in YOUR_LIST]
for your case, where you want to replace all occurrences of 1 with 10, the code snippet will be like this:
def replace_element(YOUR_LIST, set_to=10):
return [i
if i != 1 # keeps all elements not equal to one
else set_to # replaces 1 with 10
for i in YOUR_LIST]
I know this is a very old question and there's a myriad of ways to do it. The simpler one I found is using numpy
package.
import numpy
arr = numpy.asarray([1, 6, 1, 9, 8])
arr[ arr == 8 ] = 0 # change all occurrences of 8 by 0
print(arr)
List comprehension works well, and looping through with enumerate can save you some memory (b/c the operation's essentially being done in place).
There's also functional programming. See usage of map:
>>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
>>> map(lambda x: x if x != 4 else 'sss', a)
[1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]
This can be easily done by using enumerate function
code-
lst=[1,2,3,4,1,6,7,9,10,1,2]
for index,item in enumerate(lst):
if item==1:
lst[index]=10 #Replaces the item '1' in list with '10'
print(lst)