Search code examples
pythonpython-3.xlistlist-comprehension

Not understanding Python List Comprehension


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)

Eventually the result should be 6.Can please someone explain me the whole proccess and why is everything happening,because I can not get it on my own. Thank you all and look forward to get so helpful information.

As far as what i could understand it should go like this :

  1. interraction i = 3-0 = 0 and j = 0
  2. interraction i = 3-1 = 2 and j = 1
  3. interraction i = 3-2 = 1 and j = 2

but the second part i cant understand at all and would not know what to do


Solution

    1. The following [3 - i for i in range(3)] creates the list [3, 2, 1] because of [3-0, 3-1, 3-2]

    2. You repeat this operation 3 times because you have nested list comprhensions (because of j, note j value is not used), you end up with, a list containing 3 identicals lists of [3,2,1]

      # inline display
      [[3, 2, 1], [3, 2, 1], [3, 2, 1]]
      
      # two dimension display
      [[3, 2, 1], 
       [3, 2, 1], 
       [3, 2, 1]]
      
    3. Then you sum the values of positions 0,0, 1,1 and 2,2

    4. Which means the values with parenthesis in the following piece of code

      [[ (3),  2 ,  1  ], 
       [  3 , (2),  1  ], 
       [  3 ,  2 , (1) ]]
      
    5. And 3 + 2 + 1 == 6


    The following code does the same as [[3-i for i in range(3)]for j in range(3)] but some prints to help

    t = []
    # repeat 3 times
    for ite in range(3):
        temp = []
        for i in range(3):
            temp.append(3 - i)
        print("Iteration", ite, "ADD", temp, "to 't'")
        t.append(temp)