How does tuple list indexing 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:

abc

def

aei

ceg

I'm trying to understand why!

I get this, for example, for the first time through the extended version:

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

But I do not understand how (0,1,2) interacts. Can anyone suggest an explanation? Thanks.

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

+4
source share
6 answers

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

perhaps a slightly less hectic way of doing this:

 for f, s, t in W: print b[f], b[s], b[t] 
+4
source

In the frame (0,1,2) does nothing. Its tuple can be indexed in exactly the same way as a list, so b[(0,1,2)[0]] becomes b[0] with (0,1,2)[0] == 0 .

In the first step, Python executes b[row[0]] โ†’ b[(0,1,2)[0]] โ†’ b[0] โ†’ 'a'

Btw, to get multiple elements from a sequence at once, you can use the operator:

 from operator import itemgetter for row in W: print itemgetter(*row)(b) 
+4
source

Indexing a tuple simply retrieves the nth element, just like indexing an array. That is an extended version

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

equally

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

IE, the 0th element of the (0, 1, 2) tuple ( (0, 1, 2)[0] ) is 0.

0
source

for row in W:

first tuple placed in row , (0,1,2)

In other words, W[0] == (0,1,2)

 Therefore, since `row` == (0,1,2), then row[0] == 0 

So, [0]th element of b == 'a'

 b[0] == 'a' 

etc.

 b[1] == 'b' b[2] == 'c' 
0
source

Try to write down the values โ€‹โ€‹of all the variables at each step: the result you get is right.

interaction 1:

  • row is (0,1,2)
  • b [line [0]], b [line [1]], b [line [2]] - b [(0,1,2) [0], (0,1,2) [1], (0 , 1,2) [2]], == b [0], b [1], b [2]

interaction 2:

  • row is (3,4,5)
  • b [line [0]], b [line [1]], b [line [2]] - b [3], b [4], b [5]
0
source

The interactive Python shell helps you understand what is going on:

 In [78]: W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6)) In [79]: b = ['a','b','c','d','e','f','g','h','i'] In [81]: row=W[0] # The first time throught the for-loop, row equals W[0] In [82]: row Out[82]: (0, 1, 2) In [83]: row[0] Out[83]: 0 In [84]: b[row[0]] Out[84]: 'a' In [85]: b[row[1]] Out[85]: 'b' In [86]: b[row[2]] Out[86]: 'c' 
0
source

All Articles