Is it possible to index nested lists using tuples in python?

I just started with python and very soon thought if indexing a nested list with a tuple is possible. Something like: elements[(1,1)]

One example where I wanted to do this was something similar to the code below, in which I store some matrix positions that I later need to get in a tuple called an index.

 index = ( (0,0), (0,2), (2,0), (2,2) ) elements = [ [ 'a', 'b', 'c'], [ 'c', 'd', 'e'], [ 'f', 'g', 'h'] ] for i in index: print (elements [ i[0] ] [ i[1] ]) # I would like to do this: # print(elements[i]) 

This seems to be a useful feature. Is there any way to do this? Or maybe a simple alternative?

+5
source share
5 answers

Yes you can do it. I wrote a similar example:

 index = [ [0,0], [0,2], [2,0], [2,2] ] elements = [ [ 'a', 'b', 'c'], [ 'c', 'd', 'e'], [ 'f', 'g', 'h'] ] for i,j in index: print (elements [ i ] [ j ]) 

acfh

+3
source

If you really want to use tuples for indexing, you can implement your own class that extends list and overrides __getattr__ to work with tuples and uses this:

 class TList(list): def __getitem__(self, index): if hasattr(index, "__iter__"): # index is list-like, traverse downwards item = self for i in index: item = item[i] return item # index is not list-like, let list.__getitem__ handle it return super().__getitem__(index) elements = TList([ [ 'a', 'b', 'c'], [ 'c', 'd', 'e'], [ 'f', 'g', 'h'] ]) index = ( (0,0), (0,2), (2,0), (2,2) ) for i in index: print(elements[i]) 

a
from
e
h

+4
source
 # I would like to do this: # print(elements[i]) 

No, you cannot index the specific value of a nested list this way.

It would only be a little better to “unpack” the tuples if you repeat them:

Example:

 for i, j in index: print(elements[i][j]) 

See: Corrects Sequence of Sequences

0
source

If you want to print everything in elements

 index = ( (0,0), (0,2), (2,0), (2,2) ) elements = [ [ 'a', 'b', 'c'], [ 'c', 'd', 'e'], [ 'f', 'g', 'h'] ] for row in elements: for i in range(len(row)): print (row[i]) 
0
source

You can use lists:

 index = ((0, 0), (0, 2), (2, 0), (2, 2)) elements = [['a', 'b', 'c'], ['c', 'd', 'e'], ['f', 'g', 'h']] tmp = [print(elements[i][j]) for i,j in index] 
0
source

All Articles