python bug in this list implementation?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Dec 28 05:05:15 EST 2005


On Wed, 28 Dec 2005 07:29:41 +0000, Chris Smith wrote:

> Hi,
> 
> 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.

How about some advice about how to ask smart questions?

*What* is "so strange" about the behaviour -- what are you expecting? You
shouldn't expect people to read your mind and guess what behaviour you
expect, you should say "I expect X Y and Z, but I get A B and C instead."
In the future, you may not have somebody like Fredrik willing to read your
code trying to guess what you think it should do.


> code below:
> 
> import sys
> import copy
> 
> grid = []
> oGrid = []
> sGrid = []

Using global variables is not usually recommended. It is usually better to
pass local variables from function to function. That will avoid the bugs
which your code has, which Fredrik has already pointed out.


> def createGrid():
>     f = open(r"...sudoku.txt", "rb") ## see attached for the file.

Why do you need a raw string? It isn't wrong to do one, but it is rather
unusual and unnecessary.


[snip]
>     oGrid = copy.deepcopy(grid)
>     sGrid.append(copy.deepcopy(grid))

Why are you doing deepcopies of the lists? That seems to be unnecessary.

Oh, another bit of advice: any time you think you've found a bug in
Python, it almost always is a bug in your code.



-- 
Steven.




More information about the Python-list mailing list