2

I have 2 dimensional array I want to get every first element in 2 dimensional list. But when I try to using slice I have strange behavior.

arr = [[10,2],[11,3],[12,4],[13,4],[14,5]]
print(arr[:][1])

Output:

[11, 3]

arr = [[10,2],[11,3],[12,4],[13,4],[14,5]]
print(arr[1][:])

Output:

[11, 3]

Why is this behaviour? I know there are another ways for this. I would like an explanation.

Vladimir Yanakiev
  • 1,240
  • 1
  • 16
  • 25

3 Answers3

0

arr[:] is as good as object arr itself, because you are calling for a slice to include all elements.Check what this outputs

arr = [[10,2],[11,3],[12,4],[13,4],[14,5]]
print(arr[:])

It outputs the whole arr [[10, 2], [11, 3], [12, 4], [13, 4], [14, 5]]

so when you print arr[:][1], element of index 1, [11,3] is getting printed

Second one arr[1][:] understandably is the proper way to call the second row element in a 2D array with all the elements within second row element

logi
  • 66
  • 1
  • 1
  • 6
0

Think of it this way. You are currently having a 1 x 5 dimension array. In other words, you have five elements in the array. That is why no matter whether you do print(arr[:][1]) or print(arr[1][:]), you will still get [11, 3]. The first solution refers to the whole list and then find the 2nd element in the array. The latter solution refers to the 2nd element in the array, then search for all elements in the 2nd element(if the 2nd element is a list)

Perhaps it will be easier if you have a 2 x 5 dimension array.

arr = [[[10, 2], [11, 3], [12, 4], [13, 4], [14, 5]],
 [[12, 6], [4, 3], [2, 1], [14, 12], [11, 10]]]

Here, if you do print(arr[:][1]), you will get

[[12, 6], [4, 3], [2, 1], [14, 12], [11, 10]]

which is expected as it searches the whole array and returns the 2nd element (the 2nd nested list) in the array.

If you do print(arr[1][:]), you will get

[[12, 6], [4, 3], [2, 1], [14, 12], [11, 10]]

which will be the same too, because it again looks for the 2nd element(the 2nd nested list) in the array first and searches for all the elements in the nested list.

Now, back to what you want, if you only want to have every first element in the array, you can do this.

for i in range(len(arr)):
    print(arr[i][0])
    
[10, 2]
[12, 6]

Based on the loop above, you are looking for every row of the nested list in the array and return the first element in the nested list.

  • Here is an interesting post that you may benefit from: https://stackoverflow.com/q/509211/16836078 –  Apr 05 '22 at 10:04
-1

A solution for your problem

arr = [[10,2],[11,3],[12,4],[13,4],[14,5]]
print([a[0] for a in arr])

or by converting to numpy

arr = [[10,2],[11,3],[12,4],[13,4],[14,5]]
a = np.array(arr)
print(a[:,0])

2D Python list aren't numpy arrays, they can't handle slicing.

Moun
  • 325
  • 2
  • 16