python bug in this list implementation?
Fredrik Lundh
fredrik at pythonware.com
Wed Dec 28 02:50:47 EST 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
> appreciated.
> 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])
> grid.append(aLine)
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.
> sGrid.append(copy.deepcopy(grid))
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
> place.
because sGrid contains a single item; a copy of your original grid.
> print "Iteration grid: "
> for line in grid:
> print line #works fine!
as expected.
I suggest reading up on list methods and global variables in your favourite
python tutorial.
also read:
http://www.catb.org/~esr/faqs/smart-questions.html#id3001405
</F>
More information about the Python-list
mailing list