Take the 2-minute tour ×

I am using Python to generate some data and have some code like this

num = 0
for i in range(6):
    for j in range(6):
        num = random.randint(0,7)
        #some code here

Instead of producing random numbers, it just makes ten random numbers, and then repeats the sequence for the next nine sets (eg. [1,2,5,1,0,0], [1,2,5,1,0,0], ...). When I run this code again later in the program, it will give me a new set of 6 random numbers, but then repeat it for the next nine sets.

What can I do to prevent this from happening?

share|improve this question
You aren't showing enough of your code. –  FogleBird Mar 6 '12 at 2:07
The reference to ten numbers doesn't make a lot of sense with the code you have shown. More code is generally better, especially if you're assigning num into a multi-dimensional array. –  tjdett Mar 6 '12 at 2:12
add comment

1 Answer

up vote 6 down vote accepted

Stop initializing your nested lists incorrectly. [[...] * n] is wrong and will give you multiple references to the same list. Use [[...] for x in range(n)] instead.

share|improve this answer
Wow, I'm impressed you figured this out without me even showing that part of my code, this fixes the problem. –  Jonathon Mar 6 '12 at 2:27
psychic debugging –  wim Mar 6 '12 at 2:48
Impressive indeed. –  Eduardo Ivanec Mar 6 '12 at 2:52
add comment

Your Answer


