5

Given data as

data = [ [0, 1], [2,3] ]

I want to index all first elements in the lists inside the list of lists. i.e. I need to index 0 and 2.

I have tried

print data[:][0]

but it output the complete first list .i.e.

[0,1]

Even

print data[0][:]

produces the same result.

My question is specifically how to accomplish what I have mentioned. And more generally, how is python handling double/nested lists?

1

4 Answers 4

6

Using list comprehension:

>>> data = [[0, 1], [2,3]]
>>> [lst[0] for lst in data]
[0, 2]
>>> [first for first, second in data]
[0, 2]

Using map:

>>> map(lambda lst: lst[0], data)
[0, 2]

Using map with operator.itemgetter:

>>> import operator
>>> map(operator.itemgetter(0), data)
[0, 2]

Using zip:

>>> zip(*data)[0]
(0, 2)
Sign up to request clarification or add additional context in comments.

Comments

4

With this sort of thing, I generally recommend numpy:

>>> data = np.array([ [0, 1], [2,3] ])
>>> data[:,0]
array([0, 2])

As far as how python is handling it in your case:

data[:][0]

Makes a copy of the entire list and then takes the first element (which is the first sublist).

data[0][:]

takes the first sublist and then copies it.

Comments

0

The list indexing or nesting in general (be it dict, list or any other iterable) works Left to Right. Thus,

data[:][0]

would work out as

(data[:]) [0] == ([[0, 1], [2,3]]) [0]

which ultimately gives you

[0, 1]

As for possible workaronds or proper methods, falsetru & mgilson have done a good job in that regards.

Comments

0

try this:

print [x for x, y in data[:]]

1 Comment

Why the data[:]? It could just be data. (And, doesn't look like OP needs a new list for manipulation)

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.