[Tutor] simple question about lists (original) (raw)
Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jul 20 20:16:39 CEST 2004
- Previous message: [Tutor] simple question about lists
- Next message: [Tutor] simple question about lists
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Tue, 20 Jul 2004, Andy wrote:
Hello all, I'm getting ready to teach myself python. I'm going to convert an old tic tac toe game I wrote in C to get my feet wet. One question though, in C I could set up a multi dimensional array by doing
char board[3][3] I can't do multi dimensional lists in python can I? Am I right in thinking that I would need to either use a one dimensional list or get something like numeric to do this? Thanks in advance.
Hi Andy,
Yes, multidimensional lists are possible. The initialization is a little funny, though. Let me write the C equivlent first, and then a close Python translation to it.
In C, we might do something like this:
/*** Returns a 3x3 array of characters / char mallocEmptyBoard() { int i; int j; char** board = malloc(sizeof(char*) * 3); for(i = 0; i < 3; i++) { board[i] = malloc(sizeof(char) * 3); for(j = 0; j < 3; j++) { board[i][j] = '.'; } } return board; } ###
In Python, we'd have similar code, but with a little less typing:
def getEmptyBoard(): board = [None] * 3 for i in range(3): board[i] = ['.', '.', '.'] return board ###
Does this make sense?
There's an entry in the Python FAQ that talks about this a little more:
http://python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list
Good luck!
- Previous message: [Tutor] simple question about lists
- Next message: [Tutor] simple question about lists
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]