Can I set the index value of a list to a changing variable in this example?

Question:

I am a total beginner to Python and recently had a question while experimenting with lists. I have a for loop that increases a variable ‘x’ and generates a random number every time. I want to add this random number to a list, but when I try assigning the index value of the random number to x, I get this error message:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
IndexError: list assignment index out of range

Any help would be greatly appreciated!

My code:

import random as number

x = 0
values = []
while x < 9:
  values[x] = number.randint(1,91)
  x += 1

print(values)
Asked By: JxcobVFX

||

Answers:

import random as number

values = [number.randint(1,91) for _ in range(9)]

Lists do not have infinite memory, you must tell Python how many elements there are if you are going to add values at arbitrary indexes. However, you can also add or delete elements, so it is very common to start with an empty list and use .append() to add elements. Here is what you want to do instead:

import random as number

x = 0
values = []
while x < 9:
  values.append(number.randint(1,91))
  x += 1

print(values)
Answered By: Michael M.

So when you initialize the list with values = [] the list size is zero and there are no indexes. And when you do values[0] = num the zeroth index doesn’t exist, hence the error. But if you initialize your list with values = [None] * num it will create a list with None in it (num times).

import random as number

x = 0
values = [None] * 9
while x < 9:
  values[x] = number.randint(1,91)
  x += 1

print(values)

# [82, 91, 16, 80, 77, 9, 61, 78, 72]
Answered By: botaskay
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.