Jonathon Vandezande
Jonathon Vandezande

Reputation: 2476

Using random in Python

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?

Upvotes: 0

Views: 631

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

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.

Upvotes: 6

Related Questions