Reputation: 5
For a list x of lists, when I want to get the first member of all the lists in x, I type x[:][0]. But it gives me the first list in x. Can someone explain why this is so?
Here is an example.
x=[[1,2],[3,4]]
print x[0][:]
print x[:][0]
I get same answer for both x[:][0]
and x[0][:]
I get the same answer, namely [1,2]
.
I am using Python 2.6.6.
Thanks in advance.
Upvotes: 0
Views: 114
Reputation: 1729
Use one of the below statements
print x[:][1]
or
print x[1][:]
or
print x[1]
all produces the same output.
Upvotes: 0
Reputation: 304137
You are almost using the numpy syntax
>>> import numpy as np
>>> x = np.array([[1,2],[3,4]])
>>> x[:,0]
array([1, 3])
If you want to do tricky things with arrays, consider whether you should be using numpy
Upvotes: 0
Reputation: 34146
To complement @BrenBarn answer, to solve your problem you could use:
first_numbers = [l[0] for l in x]
Upvotes: 0
Reputation: 64308
x[:]
simply creates a shallow copy of x
. For this reason, x[:][0]
is the same as x[0][:]
(both are the same as x[0]
).
Numpy is perfect for what you're trying to do, though.
x = numpy.array([[1,2], [3,4]])
x[:,0]
x[0,:]
Upvotes: 1
Reputation: 251353
x[:]
just returns the contents of x. So x[:][0]
is the same as x[0]
. There is no built-in support for slicing a list of lists "vertically". You have to use a list comprehension as suggested by @squiguy's comment.
Upvotes: 3
Reputation: 1817
Try This,
x=[[1,2],[3,4]]
print x[0][0]
print x[1][0]
or
for child in x:
print child[0]
Upvotes: 0