0

I need to find the element(s) of a 2D-Array of i-th row and j-th column. I simply write T[i][j] and get correct result, but I get unintended results when I go for range of 'elements'

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
print(T[1][2])

Out[2]: 10

print(T[1:3][:2])

Out[3]: [[15, 6, 10], [10, 8, 12, 5]]

I wish to print the 2nd,3rd rows having 1st and 2nd columns, but output I got as entire 2nd and 3rd row instead.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    that kind of double indexing requires special structures, for example `numpy` arrays. Alternatively, you have to construct the result with just your relevant values instead, using old school iteration. – Paritosh Singh Apr 07 '19 at 11:51
  • 2
    You do not have an array; you have a `list`. – gmds Apr 07 '19 at 11:58
  • You get what you ask for: `T[1:3]` --> get me the 1 to 3rd sublist of `T` which happens to be `[[15, 6,10], [10, 8, 12, 5], [12,15,8,6]]` and then you ask for `[:2]` of that which happens to be `[[15, 6,10], [10, 8, 12, 5]`. – Patrick Artner Apr 07 '19 at 12:04
  • [understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Patrick Artner Apr 07 '19 at 12:05

2 Answers2

1

you can not split columns by [:2], [:2] in T[1:3][:2] means the first two elements(rows here) of T[1:3]. you can do this in numpy, but can not in list.

you can try this instead:

[t[:2] for t in T[1:3]]

output:

[[15, 6], [10, 8]]
recnac
  • 3,744
  • 6
  • 24
  • 46
1

Consider the output of the first index operation:

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
print(T[1:3])
Out: [[15, 6, 10], [10, 8, 12, 5]]

So you second indexing operation is just getting the first two elements of this, which are the compelete rows.

What you are looking for:

print([i[:2] for i in T[1:3]])
Out: [[15, 6], [10, 8]]

This first gets the outer element, and then the inner element.

GraemeC
  • 66
  • 2