I just started with python and very soon wondered if indexing a nested list with a tuple was possible. Something like: elements[(1,1)]
One example where I wanted to do that was something similar to the code below in which I save some positions of the matrix that I will later need to access in a tuple called 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])
It seems like a useful feature. Is there any way of doing it? Or perhaps a simple alternative?
If you really want to use tuples for indexing you can implement your own class that extends list
and redefines __getattr__
to work with tuples and use that:
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
c
f
h
Yes, you can do that. 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 ])
a c f h
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