Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does indexing a list with a tuple work?

I am learning Python and came across this example:

W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))
b = ['a','b','c','d','e','f','g','h','i']
for row in W:
    print b[row[0]], b[row[1]], b[row[2]]

which prints:

a b c

d e f

a e i

c e g

I am trying to figure out why!

I get that for example the first time thru the expanded version is:

print b[(0,1,2)[0]], b[(0,1,2)[1]], b[(0,1,2)[2]]

But I don't understand how the (0,1,2) is interacting. Can anyone offer an explanation? Thanks.

(this is an abbreviated version of some code for a tic tac toe game, and it works well, I just don't get this part)

like image 996
Steve Avatar asked Feb 28 '23 03:02

Steve


1 Answers

it iterates over a tuple of tuples, each row is a three-element tuple, when printing it accesses three elements of the b list by index, which is what row tuple contains.

probably, a slightly less cluttered way to do this is:

for f, s, t in W:
    print b[f], b[s], b[t]
like image 123
SilentGhost Avatar answered Mar 08 '23 07:03

SilentGhost