0

Basically say i have this array d = [1,6,7,4,9] and i want to take that content randomly and fill it into another array using a for loop a certain number of times and print the result so,

d= [1,6,7,4,9]

n = 100

s = []

for i in range(n)

   s[i] = random.choice(d)

print(s)

however, I'm getting the error that list assignment is out of range and just wanted to know what would be the best way to get this code to run. My main problem is appending the random choice into the new array.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119

2 Answers2

0
s = [random.choice(d) for _ in range(n)]

Python does not automatically grow arrays when you use indexing.

Alternatively, you could have started with

s = [None] * n

so that s starts with size n, and used the rest of your code.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • okay so i would have to create an empty array of that size then i can fill the array in? okay so that makes a lot of sense because the error was really confusing me for a second. – WeepingWillow Sep 15 '20 at 19:29
  • Correct. Or use `append`, which does grow the array, as given in the other answer. And for simple cases of building a list, list comprehension is often easier to understand and shorter. – Frank Yellin Sep 15 '20 at 19:35
0

Instead of using s[i] = random.choice(d) try out s.append(random.choice(d)). The reason you are getting the error is because you are trying to index parts of the list that don't exist yet.

Jackson
  • 78
  • 1
  • 5