I'm working through Mark Lutz's "Python," reviewing the section on lists. I understand the list comprehension so far, but ran into a snag with the matrix. I've created the matrix M as follows:<div><br>
</div><div>M = [[1, 2, 3[, [4, 5, 6], [7, 8, 9]]</div><div><br></div><div>then ran through the various comprehension examples, including:</div><div><br></div><div>diag = [M[i][i] for i in [0, 1, 2]]</div><div><br></div><div>
which, of course, gave me [1, 5, 9].</div><div><br></div><div>Then I tried creating revdiag, wanting to return [3, 5, 7], tried several different ways, never quite got what I was looking for, so I'm looking for guidance as I'm stuck on this idea. Here's the various attempts I made and the tracebacks:</div>
<div><br></div><div><div>>>> revdiag = [M[i][i] for i in [2, 1, 0]]</div><div>>>> revdiag</div><div>[9, 5, 1]</div><div># once I saw the output, this one made sense to me.</div><div><br></div><div>>>> revdiag = [M[i][j] for i in [0, 1, 2] and for j in [2, 1, 0]]</div>
<div>  File "<stdin>", line 1</div><div>    revdiag = [M[i][j] for i in [0, 1, 2] and for j in [2, 1, 0]]</div><div>                                                           ^</div><div>SyntaxError: invalid syntax</div>
<div><br></div><div>>>> revdiag = [M[i][j] for i in [0, 1, 2] and j in [2, 1, 0]]</div><div>Traceback (most recent call last):</div><div>  File "<stdin>", line 1, in <module></div><div>NameError: name 'j' is not defined</div>
<div><br></div><div>>>> revdiag = [M[i][j] for i in [0, 1, 2], for j in [2, 1, 0]]</div><div>  File "<stdin>", line 1</div><div>    revdiag = [M[i][j] for i in [0, 1, 2], for j in [2, 1, 0]]</div>
<div>                                                      ^</div><div>SyntaxError: invalid syntax</div><div><br></div><div>>>> revdiag = [M[i][j] for i in [0, 1, 2], and for j in [2, 1, 0]]</div><div>  File "<stdin>", line 1</div>
<div>    revdiag = [M[i][j] for i in [0, 1, 2], and for j in [2, 1, 0]]</div><div>                                                       ^</div><div>SyntaxError: invalid syntax</div></div><div><br></div><div>I see where the errors are occurring, but I'm not sure I fully understand why they are occurring or how to get what I'm looking for with what I presently know, which admittedly is not much. Any help would be appreciated.</div>
<div><br></div><div>regards, Richard</div><div><div><br></div>-- <br>
        
        
        <dl><dt>
        
        
        


<p style="margin-bottom:0in;line-height:0.18in" align="LEFT">
<font color="#333333"><font face="comic sans ms, sans-serif" size="4">quando om<font size="4">ni flunkus moritati</font><br></font></font></p></dt></dl><br>
</div>