Comprehension Lists

Hi. Need help with understanding the following code

t = [ [ 3 - i for i in range(3) ]  for j in range(3) ]

s= 0

for i in range (3):
      
        s = s + t [ i ] [  i ]               # please explain this line

print(s)

The answer is 6 but I don’t understand how?

So you have two for list comprehensions in one line giving you a list of lists. The outer list is just giving you three copies of the exact same inner list. If we replace the inner comprehension with a static value this is easier to see:

x = [1 for j in range(3)]
# x = [1, 1, 1]

So now we can look at what the inner comprehension is doing. It is iterating through the range(3) which is the values 0, 1, and 2. At each value i it is setting the value to 3 - i. So we end up with a list like this:

y = [3 - i for i in range(3)]
# y = [3-0, 3-1, 3-2]
# y = [3, 2, 1]

So that means we end up with three copies of that list in our variable t:

t = [y, y, y]
# t = [[3, 2, 1], [3, 2, 1], [3, 2, 1]]

With that, do you now understand the final part that does the calculation?

PS: this is really bad programming because it is doing needless work and making things very opaque. I think it is written this way just to test your knowledge of list comprehensions.

Thank you so much. Can you also please explain the following line of code as well

for i in range (3):
      
        s = s + t [ i ] [  i ]               

print(s)

This code is from the previous programme and gives 6 .I don’t understand what t[ i ] [ i ]
means?

Since t is a list of lists, that is just indexing into the outer list and then into the inner list. Consider a list of lists like this: z = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]. If I just index into the outer list I could get the first inner list like this:

first = z[0]
# first = [11, 12, 13]

Indexing into that list allows us to access the elements:

result = z[0][1]
# result = first[1] = 12

So you have a for loop iterating from 0 to 2 through your list of lists selecting the diagonal elements (the i element of the i outer list). If that for loop were applied to my example, we would get:

s = 0 + z[0][0] + z[1][1] + z[2][2]
# s = 11 + 22 + 33 = 66

Hope that helps!

Thank you so much .It’s a great help.

1 Like