Most pythonic and/or performant way to assign a single value to a slice?

python, slice

Solution

I think there's no straight out of the box feature in Python to do this. I like your second approach, but keep in mind that there's a tradeoff between space and time. This is a very good reading recommended by @user4815162342: Python Patterns - An Optimization Anecdote.

Anyhow, if this is an operation you'll be performing eventually in your code, I think your best option is to wrap it inside a helper function:

def setvalues(lst, index=0, value=None):
    for i in range(index, len(lst)):
        lst[i] = value

>>>l=[1,2,3,4,5]
>>>setvalues(l,index=2)
>>>l
>>>[1, 2, None, None, None]

This has some advantages:

- The code is refactored inside a function, so easy to modify if you change your mind about how to perform the action.

- You can have several functions that accomplish the same target and therefore can measure their performance.

- You can write tests for them.

- Every other advantage you can get by refactoring :)

Since IMHO there's no straight Python future for this action, this is the best workaround I can imagine.

Hope this helps!

Problem

I want to assign a single value to a part of a list. Is there a better solution to this than one of the following? Maybe most performant but somehow ugly: ``` >>> l=[0,1,2,3,4,5] >>> for i in range(2,len(l)): l[i] = None >>> l [0, 1, None, None, None, None] ``` Concise (but I don't know if Python recognizes that no rearrangement of the list elements is necesssary): ``` >>> l=[0,1,2,3,4,5] >>> l[2:] = [None]*(len(l)-2) >>> l [0, 1, None, None, None, None] ``` Same caveat like above: ``` >>> l=[0,1,2,3,4,5] >>> l[2:] = [None for _ in range(len(l)-2)] >>> l [0, 1, None, None, None, None] ``` Not sure if using a library for such a trivial task is wise: ``` >>> import itertools >>> l=[0,1,2,3,4,5] >>> l[2:] = itertools.repeat(None,len(l)-2) >>> l [0, 1, None, None, None, None] ``` The problem that I see with the assignment to the slice (vs. the for loop) is that Python maybe tries to prepare for a change in the length of "l". After all, changing the list by inserting a shorter/longer slice involves copying all elements (that is, all references) of the list AFAIK. If Python does this in my case too (although it is unnecessary), the operation becomes O(n) instead of O(1) (assuming that I only always change a handful of elements).

Original source