0

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.

1
  • 1
    Why not just [x[0] for x in nested]? Commented Nov 19, 2013 at 6:28

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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,:]

Comments

0

Try This,

x=[[1,2],[3,4]]
print x[0][0]
print x[1][0]

or

for child in x:
    print child[0]

Comments

0

To complement @BrenBarn answer, to solve your problem you could use:

first_numbers = [l[0] for l in x]

Comments

0

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

Comments

0

Use one of the below statements

print x[:][1]

or

print x[1][:]

or

print x[1]

all produces the same output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.