1

I want to replace the elements in list at the positions given in replacement indices with new value. For example, if the given list is replace_elements([1,2,3,4,5,6,7,8],[0,4,3],0) then the outcome should be [0, 2, 3, 0, 0, 6, 7, 8]. I tried several approaches but none of them seems to work. I tried following code:

for i in new_value:
   list_a[i] = replacement_indices
return new_value
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Related: [How to replace values at specific indexes of a python list?](https://stackoverflow.com/questions/7231204/how-to-replace-values-at-specific-indexes-of-a-python-list) – jpp Dec 11 '18 at 18:03
  • 1
    @jpp more like a duplicate right? you can close I'm not going to yell – Jean-François Fabre Dec 11 '18 at 18:20
  • @Jean-FrançoisFabre, Slightly different IMO because that post supports different values for each index. While this doesn't matter for `list`, it may matter for NumPy (for example). Not that I'm suggesting we offer a NumPy solution here :). – jpp Dec 11 '18 at 18:21

2 Answers2

3

TL;DR: a list comprehension approach which doesn't work in-place:

just decide between replacement value or original within a ternary expression based on the index in a list comprehension:

def replace_elements(inlist, indexes, replvalue):
    return [replvalue if i in indexes else x for i,x in enumerate(inlist)]

print(replace_elements([1,2,3,4,5,6,7,8],[0,4,3],0))

result:

[0, 2, 3, 0, 0, 6, 7, 8]

for big index lists, [0,4,3] should be a set ({0,4,3}) for faster lookup.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

You're putting replacment_indices and new_value in the wrong places. You should iterate through replacement_indices and assign new_value to the list at each specified index instead:

for i in replacement_indices:
   list_a[i] = new_value

There's also no need to return anything since you're modifying the list in-place, which means that after the loop list_a would be modified per specifications already.

blhsing
  • 91,368
  • 6
  • 71
  • 106