Set Item At Multiple Indexes In A List
I am trying to find a way to use a list of indexes to set values at multiple places in a list (as is possible with numpy arrays). I found that I can map __getitem__ and a list of i
Solution 1:
The difference between the get
and set
case is that in the get
case you are interested in the result of map
itself, but in the set
case you want a side effect. Thus, you never consume the map
generator and the instructions are never actually executed. Once you do, b_list
gets changed as expected.
>>> put_map = map(b_list.__setitem__, idxs, ['YAY', 'YAY'])
>>> b_list
['a', 'b', 'c']
>>> list(put_map)
[None, None]
>>> b_list
['YAY', 'YAY', 'c']
Having said that, the proper way for get
would be a list comprehension and for set
a simple for
loop. That also has the advantage that you do not have to repeat the value to put in place n times.
>>> for i in idxs: b_list[i] = "YAY">>> [b_list[i] for i in idxs]
['YAY', 'YAY']
Post a Comment for "Set Item At Multiple Indexes In A List"