Steven D'Aprano <steve+pyt...@pearwood.info> added the comment:
If you know about timeit, why aren't you using it? In any case, I have just ran your nested_lists.py file, and on my computer, the last version with zip is the fastest version: 0 transpose1_0(lT) Time = 1.0627508163452149e-05 7 zip(*lT) Time = 1.5511512756347657e-06 1.55e-6 is smaller than 1.06e-5: py> 1.55e-6 < 1.06e-5 True Smaller times are faster, and the first version transpose1_0 takes nearly seven times longer to run than the last version with zip. As for the other comments, the purpose of the tutorial is to teach the language in the simplest way possible. It is aimed at beginners, not intermediate or expert programmers. The purpose of this section is to demonstrate the basic features of list comprehensions, not to overwhelm the beginner with complicated details. Making the example more complicated so that it is a tiny bit faster would not a good tradeoff for the tutorial, but in fact all the more complicated versions are slower, not faster. You are also confused about the structure of comprehensions. The comprehension consists of expression-part for-part (optional for- and if-parts) There is no else-part in the comprehension, and the for-part always comes before any if-part. Your code: row[j] if j < len(row) else 0 is not an "if statement" as you call it, neither is it part of the comprehension syntax. It is the expression-part of the comprehension, containing a ternary if-expression. It is not part of the structure of the comprehension. See the full language specification, in particular the grammar: https://docs.python.org/3.9/reference/grammar.html We could re-write the if-expression like this: (j < len(row)) and row[j] or 0 That doesn't mean that comprehensions consist of an "and" part followed by an "or" part followed by a for-part. The "and" and "or" are just part of the expression part of the comprehension. Adding this level of technical detail and complexity to an introductory tutorial aimed at beginners would not be a good idea. ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue41590> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com