You've said you "want to pull the first three values from the first, second, and third rows". So instead of creating the three lists k0
, k1
, and k2
separately, you could put that in your iteration and operate directly on K
, by first slicing the first 3 columns.
A.
concatenated_ko = []
for row in K[:3]:
concatenated_ko.extend(row[:3])
B. or, if you want to use indexes:
concatenated_ko = []
for idx in range(3):
concatenated_ko.extend(K[idx][:3])
C. And suppose K is a 5x5 array:
>>> K
array([[ 5, 12, 10, 70, 4],
[102, 6, 120, 60, 22],
[150, 100, 110, 2, 150],
[ 15, 20, 22, 70, 30],
[ 20, 55, 1, 70, 1]])
Then to get the first 3 columns of the first 3 rows as a single array, you can use ndarray.flatten()
:
>>> K[:3, :3].flatten()
array([ 5, 12, 10, 102, 6, 120, 150, 100, 110])
>>> K[:3, :3].flatten().tolist()
[5, 12, 10, 102, 6, 120, 150, 100, 110]
Another option, not recommended: To make a minor modification to your original code, use eval
to get the list from its variable name, and use extend
instead of append
:
# with k0, k1, k2 setup as per your question
for j in range(0,3):
k = "k"+str(j)
concatenated_ko.extend(eval(k))