What's going on here? Repeating rows in random list of lists.

Posted by Jesse Aldridge on Stack Overflow See other posts from Stack Overflow or by Jesse Aldridge
Published on 2010-06-14T00:29:36Z Indexed on 2010/06/14 0:32 UTC
Read the original article Hit count: 486

Filed under:
|
|

I expected to get a grid of unique random numbers. Instead each row is the same sequence of numbers. What's going on here?

from pprint import pprint
from random import random

nrows, ncols = 5, 5
grid = [[0] * ncols] * nrows
for r in range(nrows):
    for c in range(ncols):
        grid[r][c] = int(random() * 100)
pprint(grid)

Example output:

[[64, 82, 90, 69, 36],
 [64, 82, 90, 69, 36],
 [64, 82, 90, 69, 36],
 [64, 82, 90, 69, 36],
 [64, 82, 90, 69, 36]]

© Stack Overflow or respective owner

Related posts about python

Related posts about random