2D-Lists__intro
2D-Lists__intro
As you know the elements of your list can be anything, even lists and tuples
e.g. student = ["Jake", 16, ["Math", "Comp.Sci", "Physics"]]
This is valid and some people will do this in Python. I don't like it much. If I want to create an object that
represents a person I'll make a person class and make an instance of it. A more complicated list that I do like
is a list of lists. e.g.
How this board could be drawn on the screen is just a personal preference, as long as I am consistent, it will
work out. I like to be consistent with the way things are already drawn on the screen.
The advantage of using a 2-dimensional list is that I can easily separate the issue of finding the row/column
locations from doing something with it. It also can make checking rows and columns easier. This example
is fairly small, so you might be tempted to use 9 variables. What if we were playing connect4 instead; that's
a 7x6 board, or 42 variables.
You can use list comprehension to create a 3x3 grid for a tic-tac-toe game:
e.g.
board=[[0 for i in range(3)] for j in range(3)]
Try the following program (Creating connect4 board)
from pprint import pprint #pprint is used to print 2D lists in rows and columns
pprint(connect)
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]