TMWP
TMWP

Reputation: 1625

Python complex object indexing - trouble accessing specific nested element

This is a training example that may or may not have application in the real world. I have simplified it just to illustrate the problem. Once built, I was having difficulty finding the right syntax to index a sub element. Hoping someone can crack this ... just for the learning value.

import numpy as np
import pandas as pd

# some simple arrays:
simp1=np.array([[1,2,3,4,5]])
simp2=np.array([[10,9,8,7,6]])
simp3=[11,12,13]

trueSimp1=np.array([10,9,8,7,6])

crazyList = [simp1, simp2, simp3, trueSimp1]

We can access the first element of the last object with:

crazyList[3][0]

We can view the whole first object with:

crazyList[0]

But how to get just a sub-element within the first object? I tried many failed ideas of [0][1], [0,1], [[0]], [[0][1]] etc... and can't seem to find the right one to get at it. Just for the learning, I would like add this answer to the notes I am building.

Upvotes: 1

Views: 55

Answers (1)

miradulo
miradulo

Reputation: 29690

For learnings' sake, you should know that this list is ideally a structure you would never ever have to deal with.

Your issue is that the first element in crazyList has an empty level of nesting (notice the extra square brackets). That is, the ndarray contains another ndarray containing the actual elements.

>>> crazyList[0]
array([[1, 2, 3, 4, 5]])
>>> type(crazyList[0][0])
numpy.ndarray

Hence to access individual elements, you need to index the additional layer.

>>> crazyList[0][0][1]
2

Upvotes: 2

Related Questions