user3007527
user3007527

Reputation: 5

error while slicing in list of lists in python

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

Answers (6)

user2486495
user2486495

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

John La Rooy
John La Rooy

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

Christian Tapia
Christian Tapia

Reputation: 34146

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

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

Upvotes: 0

shx2
shx2

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

BrenBarn
BrenBarn

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

Syed Habib M
Syed Habib M

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

Related Questions