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?
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.
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:
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?
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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With