How is this list comprehension evaluated?

Roy Smith roy at panix.com
Mon Sep 16 20:04:32 EDT 2013


In article <eae87c72-f62d-4815-bb69-ca862ff78f1e at googlegroups.com>,
 Arturo B <a7xrturodev at gmail.com> wrote:

> Hello, I'm making Python mini-projects and now I'm making a Latin Square
> 
> (Latin Square: http://en.wikipedia.org/wiki/Latin_square)
> 
> So, I started watching example code and I found this question on 
> Stackoverflow: 
> 
> http://stackoverflow.com/questions/5313900/generating-cyclic-permutations-redu
> ced-latin-squares-in-python
> 
> 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)]

You can re-write any list comprehension as a for loop.  In this case you 
have to un-wrap this one layer at a time.  First step:

    a = [1, 2, 3, 4]
    n = len(a)
    temp1 = []
    for j in range(n):
        temp2 = [a[i - j] for i in range(n)]
        temp1.append(item)

then, unwrap the next layer:

    a = [1, 2, 3, 4]
    n = len(a)
    temp1 = []
    for j in range(n):
        temp2 = []
        for i in range(n):
             temp3 = a[i - j]
             temp2.append(temp3)
        temp1.append(item)

Does that make it any easier to understand?



More information about the Python-list mailing list