Home > database >  The following snippet gives 6 and I do not understand why
The following snippet gives 6 and I do not understand why

Time:03-08

What is the output of the following snippet?

t = [[3-i for i in range(3)] for j in range (3)]
s = 0
for i in range(3):
    s  = t[i][i]
print(s)

CodePudding user response:

Line 1 creates a 3x3 matrix (or list of lists) containing the integers 3, 2, 1 in each row. Lines 2-3 assign the sum of the diagonal 3, 2, 1 of the matrix to s. That's 6.

t = [[3-i for i in range(3)] for j in range (3)] # t = [[3-0,3-1,3-2], [3-0,3-1,3-2], [3-0,3-1,3-2]] = [[3,2,1], [3,2,1], [3,2,1]]
s = 0
for i in range(3):
    s  = t[i][i] # s = sum of diagonal of t = 3   2   1 = 6
print(s)

CodePudding user response:

The first line creates a nested list t that contains three lists, each of them [3, 2, 1]. The for loop sums up the values t[0][0], t[1][1] and t[2][2] from this nested list. It's actually quite straightforward once you realise that lists can contain other lists.

  • Related