Search code examples
pythonlistreplacecopy

Replacing a list item and returning a copy of the list (in one line) with Python


I'm working on something that uses search, so each recursive call needs a separate copy of a list but with a single element replace. I'd like to do it (neatly) in one line, and so far I have this which goes in the recursive call:

[new_value if x == replace_index else my_list[x] for x in range(len(my_list))]

But is there a neater way to do this, potentially using some built in function I'm missing?


Solution

  • Maybe something like this:

    [new_value if i == replace_index else element
     for i, element in enumerate(my_list)]
    

    or:

    new_list = my_list[:]
    new_list[replace_index] = new_value
    

    or:

    new_list = my_list[:replace_index] + [new_value] + my_list[replace_index+1:]
    

    In this case, I think I prefer the second option (probably is also the fastest one).