Shanks Shanks - 4 months ago 10
Python Question

Printing a column of a 2-D List in Python

Suppose if

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


Then
A[0][:]
prints
[1, 2, 3]


But why does
A[:][0]
print
[1, 2, 3]
again ?

It should print the column
[1, 4, 7]
, shouldn't it?

Answer

[:] is equivalent to copy.

A[:][0] is the first row of a copy of A. A[0][:] is a copy of the first row of A.

The two are the same.

To get the first column: [a[0] for a in A] Or use numpy and np.array(A)[:,0]