Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing a nested list in python

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?

like image 218
aiao Avatar asked Dec 02 '13 16:12

aiao


People also ask

How do you find the index of a nested list?

The indices for the elements in a nested list are illustrated as below: You can access individual items in a nested list using an index in multiple square brackets. Negative List Indexing In a Nested List. You can access a nested list by negative indexing as well. A negative list index counts from the end of the nested list.

How to access a nested list in Python?

You can access a nested list by negative indexing as well. Negative indexes count backward from the end of the list. So, L [-1] refers to the last item, L [-2] is the second-last, and so on. The negative indexes for the items in a nested list are illustrated as below:

How to flatten a nested list in Python?

By using list comprehension, we can flatten the nested list. This is one way of doing it. First, iterate through the nested list, then iterate through the sub_list and get each element. 4. Find the index of all occurrences of an item in a Python nested list?

How do I remove items from a nested list in Python?

Remove items from a Nested List If you know the index of the item you want, you can use pop () method. It modifies the list and returns the removed item. L = ['a', ['bb', 'cc', 'dd'], 'e'] x = L.pop (1) print(L) # Prints ['a', ['bb', 'dd'], 'e'] # removed item print(x) # Prints cc


2 Answers

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)
like image 192
falsetru Avatar answered Sep 20 '22 05:09

falsetru


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.

like image 21
mgilson Avatar answered Sep 18 '22 05:09

mgilson