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?
[:]
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]
When you don't specify a start or end index Python returns the entire array:
A[:] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[:]
matches the entire list.
So A[:]
is the same as A
. So A[0][:]
is the same as A[0]
.
And A[0][:]
is the same as A[0]
.
Note that [:]
just gives you a copy of all the content of the list. So what you are getting is perfectly normal. I think you wanted to use this operator as you would in numpy or Matlab. This does not do the same in regular Python.
A[0]
is [1, 2, 3]
Therefore A[0][:]
is also [1, 2, 3]
A[:]
is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Therefore A[:][0]
is [1, 2, 3]
If you wanted the first column you should try:
[e[0] for e in A]
# [1, 4, 7]
A[:]
returns a copy of the entire list. which is A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A[:][0]
Thus selects [1, 2, 3]
.
If you want the first column, do a loop:
col = []
for row in A:
col.append(row[0])
A is not a 2-D list: it is a list of lists. In consideration of that:
A[0]
is the first list in A:
>>> A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> A[0]
[1, 2, 3]
Consequently, A[0][:]
: is every element of the first list:
>>> A[0][:]
[1, 2, 3]
A[:]
is every element of A, in other words it is a copy of A:
>>> A[:]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Consequently, A[:][0]
is the first element of that copy of A.
>>> A[:][0]
[1, 2, 3]
To get what you want, use numpy:
>>> import numpy as np
>>> A = np.array( [[1, 2, 3], [4, 5, 6], [7, 8, 9]] )
A
is now a true two-dimensional array. We can get the first row of A
:
>>> A[0,:]
array([1, 2, 3])
We can similarly get the first column of A
:
>>> A[:,0]
array([1, 4, 7])
`
A is actually a list of list, not a matrix. With A[:][0]
You are accessing the first element (the list [1,2,3]
) of the full slice of the list A. The [:]
is Python slice notation (explained in the relevant Stack Overflow question).
To get [1,4,7] you would have to use something like [sublist[0] for sublist in A]
, which is a list comprehension, a vital element of the Python language.