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.
JavaScript
x
12
12
1
index = ( (0,0), (0,2), (2,0), (2,2) )
2
3
elements = [ [ 'a', 'b', 'c'],
4
[ 'c', 'd', 'e'],
5
[ 'f', 'g', 'h'] ]
6
7
for i in index:
8
print (elements [ i[0] ] [ i[1] ])
9
10
# I would like to do this:
11
# print(elements[i])
12
It seems like a useful feature. Is there any way of doing it? Or perhaps a simple alternative?
Advertisement
Answer
Yes, you can do that. I wrote a similar example:
JavaScript
1
9
1
index = [ [0,0], [0,2], [2,0], [2,2] ]
2
3
elements = [ [ 'a', 'b', 'c'],
4
[ 'c', 'd', 'e'],
5
[ 'f', 'g', 'h'] ]
6
7
for i,j in index:
8
print (elements [ i ] [ j ])
9
a c f h