Matt Johnson
Matt Johnson

Reputation: 55

Python: retrieve an item from a list of lists of lists

I have a list of lists of lists, and I want to know the right way to retrieve a particular item from a bottom-level list.

For example, say I want to print 100:

tree1 = [[0, 0, 0], [1, 1, 1], [2, 100, 2]]
tree2 = [[[0, 0 ,0], [1, 1, 1], [2, 100, 2]], [[3, 3, 3], [4, 4, 4], [5, 5, 5]]]

print(tree1[3][2])
print(tree2[1][3][2])

The first example works, but the second does not. How does Python handle indexing for "higher-dimensional" nested lists?

Upvotes: 0

Views: 646

Answers (3)

iGian
iGian

Reputation: 11183

A way to "see" index of a list is to iterate over it enumerating items, enumerate returns the element and the index.

So for example:

for index, element in enumerate(tree1):
  print (index, element)

# (0, [0, 0, 0])
# (1, [1, 1, 1])
# (2, [2, 100, 2])

Where you can see that index starts at 0. When you call print(tree1[1]), you get #=> [1, 1, 1]

To dig deeper in the list, you can iterate over nested elements, for example (I change the name of the variables):

for i_row, row in enumerate(tree1):
  for i_col, cell in enumerate(row):
    print(i_row, i_col, cell)

Returns:

# (0, 0, 0)
# (0, 1, 0)
# (0, 2, 0)
# (1, 0, 1)
# (1, 1, 1)
# (1, 2, 1)
# (2, 0, 2)
# (2, 1, 100)
# (2, 2, 2)

So, calling for example print(tree1[2][1]), returns #=> 100

The same with tree2, where you can dig down one level more.

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71560

Python indexing starts at 0, so example:

>>> a=[1,2,3]
>>> a[0]
1
>>> a[1]
2
>>> a[2]
3

So your code could be:

print(tree1[2][1])
print(tree2[0][2][1])

Upvotes: 0

Brandon Schabell
Brandon Schabell

Reputation: 1915

Actually, neither of these should work. In Python, lists are indexed starting at 0. That means to print 100 in tree1 and tree2, you would need to run:

print(tree1[2][1])
print(tree2[0][2][1])

Upvotes: 1

Related Questions