Tip 26 Transpose with zip()

Pythonic Programming — by Dmitry Zinoviev (35 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 sum() Almost Anything | TOC | Discover All Characters in One Place 👉

★★2.7, 3.4+ If you have never programmed Tic-Tac-Toe, you missed one of the most “classic” exercises — it’s almost like never having printed “Hello, world!” But even then, you probably know that the game field is often stored in a three-by-three array-like structure.

The core Python does not support arrays or matrices (they are available through the modules array and numpy, both outside of this book’s scope). However, Python has nested lists, lists of lists, which are almost perfect for a small game. A list of three-element lists of spaces is a reasonable data structure for a three-by-three field:

​ SIZE = 3
​ field = [[​' '​] * SIZE ​for​ _ ​in​ range(SIZE)]

(Tip 12, Avoid “Magic” Values and Tip 10, Mark Dummy Variables explain the significance of the constant SIZE and the identifier _. Tip 89, Treat Variables as References advises why the seemingly obvious expression [[’ ’] * SIZE] * SIZE] is an unforgivable mistake.) Each inner list represents a row of the field.

The game ends when one of the rows, one of the columns, or one of the diagonals has three identical symbols: three crosses or three circles. You can check if the condition is true for any row by counting the symbols in each row and calling the namesake built-in function any:

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.