Jason Midkiff - 7 months ago 20
Python Question

# Creating 2-D list in python using random numbers.

``````import random

rows = 3
cols = 3
virus = [0,0,0,0,0,1,2]
virus_level = random.choice(virus)
first_gen = []
row =[]
for rownum in range(rows):
for colnum in range(cols):
virus_level = random.choice(virus)
row.append(virus_level)
first_gen.append(row)
``````

I need to create a 2-D list using the random numbers from the list virus. This is what I have so far, the numbers aren't in random order and the list prints out as a 9 by 3, not 3 by 3. Some pointers in the right direction would be nice.

You need to reset row on every loop. Taking your code snippet as-is, if you just take the `row =[]` line and put it inside of the outer loop, that should give you the right results.

``````import random

rows = 3
cols = 3
virus = [0,0,0,0,0,1,2]
virus_level = random.choice(virus)
first_gen = []
for rownum in range(rows):
row = []
for colnum in range(cols):
virus_level = random.choice(virus)
row.append(virus_level)
first_gen.append(row)

print first_gen  # [[2, 0, 0], [0, 0, 0], [1, 0, 0]]
``````