python bug in this list implementation?
fredrik at pythonware.com
Wed Dec 28 08:50:47 CET 2005
Chris Smith wrote:
> I've been working on some multi-dimensional lists and I've encountered some
> very strange behaviour in what appears to be simple code, I'm using python
> 2.4.2 and IDLE. If anyone can tell me why it's behaving so strange please
> let me know, any improvements to my general coding style are also
> code below:
> import sys
> import copy
> grid = 
> oGrid = 
> sGrid = 
> def createGrid():
> f = open(r"...sudoku.txt", "rb") ## see attached for the file.
> for line in f:
> aLine = line.strip().split(',')
> if aLine != [""]:
> for i in xrange(len(aLine)):
> aLine[i] = int(aLine[i])
at this point, grid contains a list of lists.
> oGrid = copy.deepcopy(grid)
if you assign to a name inside a function, that name is considered to be
*local*, unless you specify otherwise. in other words, this doesn't touch
the *global* (module-level) oGrid variable.
here you add a list of lists to a list. the result is a list with a single item.
> def printGrid():
> print "original grid:"
> for line in oGrid:
> print line #why doesn't this print anything?
because the *global* oGrid is still empty.
> print "S grid:"
> for line in sGrid:
> print line #this prints the grid but the formatting is all over the
because sGrid contains a single item; a copy of your original grid.
> print "Iteration grid: "
> for line in grid:
> print line #works fine!
I suggest reading up on list methods and global variables in your favourite
More information about the Python-list