Reputation: 333
Say I have two lists A which has 10 elements, and I want to assign the list B = [x1, y1]
to values in A. If the values are sequential, it is straightforward e.g. A[1:3] = B
. But what if my indices are non-sequential? In MATLAB I can do A([3 10]) = B;
, is there an equivalently clean Python solution? The for loop to do this is straightforward, but I am wondering if I am missing something more "Pythonic".
Upvotes: 0
Views: 75
Reputation: 9676
Whenever I try to emulate some Matlab functionality in Python I use numpy. Using a numpy array
instead of a python list
allows to you get the functionality you are looking for with almost the same syntax as Matlab:
In [1]: import numpy as np
In [2]: a = np.arange(10)
In [3]: b = [200, 300]
In [4]: a[[2, 9]] = b
In [5]: a
Out[5]: array([ 0, 1, 200, 3, 4, 5, 6, 7, 8, 300])
Upvotes: 2
Reputation: 159915
Slightly more verbose, but you can use tuple unpacking to assign to new indices:
>>> x = range(1, 11)
>>> x[3], x[7] = 99, 999
>>> x
[1, 2, 3, 99, 5, 6, 7, 999, 9, 10]
Upvotes: 3