How is this list comprehension evaluated?

Michael Torrie torriem at gmail.com
Mon Sep 16 10:20:44 EDT 2013


On 09/16/2013 07:43 AM, Arturo B wrote:
> It uses a list comprenhension to generate the Latin Square, I'm am a newbie to Python, and  I've tried to figure out how this is evaluated:
> 
>     a = [1, 2, 3, 4]
>     n = len(a)
>     [[a[i - j] for i in range(n)] for j in range(n)]
> 
> I don't understand how the "i" and the "j" changes.
> On my way of thought it is evaluated like this:

It helps to convert it to a conventional for loop to see how it works:

a = [1, 2, 3, 4]
n = len(a)

resultj = []

for j in range(n):
    resulti = []

    for i in range(n):
        resulti.append(a[i-j])

    resultj.append(resulti)




More information about the Python-list mailing list