I have a list: mylist = [0, 0, 0, 0, 0]
I only want to replace selected elements, say the first, second, and fourth by a common number, A = 100.
One way to do this:
mylist[:2] = [A]*2
mylist[3] = A
mylist
[100, 100, 0, 100, 0]
I am looking for a one-liner, or an easier method to do this. A more general and flexible answer is preferable.
Especially since you’re replacing a sizable chunk of the
list, I’d do this immutably:It’s intentional in Python that making a new
listis a one-liner, while mutating alistrequires an explicit loop. Usually, if you don’t know which one you want, you want the newlist. (In some cases it’s slower or more complicated, or you’ve got some other code that has a reference to the samelistand needs to see it mutated, or whatever, which is why that’s “usually” rather than “always”.)If you want to do this more than once, I’d wrap it up in a function, as Volatility suggests:
I personally would probably make it a generator so it yields an iteration instead of returning a list, even if I’m never going to need that, just because I’m stupid that way. But if you actually do need it:
Or: