List assignment, unexpected result
Bengt Richter
bokr at oz.net
Sat Jul 13 00:57:03 EDT 2002
On Wed, 10 Jul 2002 22:33:02 +0100, "Steve Coates" <steve.coates at virgin.net> wrote:
>Thanks for the help. I think my favourite solution was
>
>grid = [['.' * 4] for i in range(4)]
>
I think you should take Dave Reed's advice and use
grid = [['.',] * 4 for i in range(4)]
though you can leave out the the comma, since ['.',] is a list, not a one-element tuple
>but I'll need to read up on the syntax. I haven't seen this
>use of a for loop before.
>
As someone pointed out, it's a list comprehension, not a for loop.
Your "favorite solution" is a little different from Dave's suggestion
(as you've probably found out by now):
>>> grid = [['.' * 4] for i in range(4)]
>>> grid
[['....'], ['....'], ['....'], ['....']]
>>> grid [0][0] = '0'
>>> grid
[['0'], ['....'], ['....'], ['....']]
IOW, even trivial things are worth testing ;-)
vs. moving a right bracket to get Dave's version (w/o comma):
>>> grid = [['.' * 4] for i in range(4)]
:
v
,-<-'
v
>>> grid = [['.'] * 4 for i in range(4)]
>>> grid
[['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']]
>>> grid [0][0] = '0'
>>> grid
[['0', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']]
or to finish,
>>> for i in range(4): grid[i][i] = i
...
>>> grid
[[0, '.', '.', '.'], ['.', 1, '.', '.'], ['.', '.', 2, '.'], ['.', '.', '.', 3]]
Regards,
Bengt Richter
More information about the Python-list
mailing list