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
list
is a one-liner, while mutating alist
requires 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 samelist
and 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:
Numpy supports this if you're not opposed to using an
np.ndarray
:I like a list comprehension:
Not a huge fan of this one, but you could try this (although I think all of the above are much more concise and easy to read):
Aside from the questionable readability and need for an import, @abarnert pointed out a few additional issues, namely that
map
still creates an unnecessary list (which is discarded with the_
but created nonetheless) and that it won't work in Python 3 becausemap
returns an iterator in Python 3.x. You can use the six module to simulate the behavior ofmap
in Python 3.x from Python 2.x, and in combination withcollections.deque
(again as suggested by @abarnert), you can achieve the same output without creating the additional list in memory because adeque
that can contain a maximum of0
items will discard everything it receives from themap
iterator (note that withsix
,map
is simulated by usingitertools.imap
).Again, there is absolutely no need to ever use this - every solution above/below is better :)
It's definitely a more general solution, not a one-liner though. For example, in your case, you would call:
Is this what you're looking for? Make a list of the indexes you want to change, and then loop through that list to change the values.