Reputation: 1
This is my code:
import random
fixed_set = random.sample(range(1, 11), 6)
test = [[random.sample(range(1, 11), 6)] for x in range(5)]
for x in range(5):
for j in range(6):
print (test[x][j])
In line 7 "print (test[x][j])" I get this error "IndexError: list index out of range" and I don't exactly understand why it is happening and how to fix it. Any help would be appreciated.
Upvotes: 0
Views: 390
Reputation: 2159
import random
fixed_set = random.sample(range(1, 11), 6)
test = [random.sample(range(1, 11), 6) for x in range(5)]
print (fixed_set)
print (test)
for x in range(5):
for j in range(6):
print (test[x][j])
This one helpful for you.
You Have to make test
lists of list carefully.
Another Method in which just change print
method.
import random
fixed_set = random.sample(range(1, 11), 6)
test = [[random.sample(range(1, 11), 6)] for x in range(5)]
print (fixed_set)
print (test)
for x in range(5):
for j in range(6):
print (test[x][0][j])
There are some change in the print
method according to your test
list.
Upvotes: 0
Reputation: 1258
random.sample(range(1, 11), 6)
returns a list itself and no need to use []
around that.
Try this:
import random
test = [random.sample(range(1, 11), 6) for x in range(5)]
for x in range(5):
for j in range(6):
print (test[x][j])
Upvotes: 1
Reputation: 1081
Try to debug your script.
The "test" variable is a list of lists of a single item which in turn is just a list of 6 integers in range 1-10 (inclusive).
For example:
[[[3, 2, 8, 9, 7, 6]], [[7, 1, 3, 2, 9, 5]], [[10, 9, 2, 4, 5, 1]], [[5, 7, 9, 3, 4, 1]], [[10, 9, 2, 7, 6, 3]]]
Is this what you want? Maybe you just want it to be a list of 6-elements lists; in which case, you have to remove the set of squares around [random.sample(range(1, 11), 6)]
By the way: fixed_set is never used, in your code.
Upvotes: 0
Reputation: 14689
random.sample(range(1, 11), 6)
is already returning a list, yet you are wrapping it with another list in [[random.sample(range(1, 11), 6)] for x in range(5)]
, so change that line to this [random.sample(range(1, 11), 6) for x in range(5)]
and your code should be fine:
import random
fixed_set = random.sample(range(1, 11), 6)
test = [random.sample(range(1, 11), 6) for x in range(5)]
for x in range(5):
for j in range(6):
print (test[x][j])
Upvotes: 0