1

I'm really new to Python, and I'm trying to write a python program that asks the user how many pieces of data they have, and then the user inputs that data which goes into an array. The problem I'm running into is that I must define the length of the array for the program to work, but I want the user to define that as "x". That way, the user can put a specific amount of data into the array.

Here's what I have

i = 0

x = int(input("How many iterations"))

odds = [] #This is where I do not know how to define the array as whatever amount of pieces of data the user wants.

while i < x:
    odds[i] = input("Enter number ")
    i = i+1

The error message says

IndexError: list assignment index out of range

I'm pretty new to programming, so any help would be much appreciated. I totally understand that I may be going about this problem TOTALLY the wrong way, so please let me know how you would do it. Thanks!

MarianD
  • 13,096
  • 12
  • 42
  • 54
  • 1
    Just do `odds.append(input("Enter number"))` instead – Randy Nov 07 '18 at 20:20
  • 1
    Possible duplicate of [Create an empty list in python with certain size](https://stackoverflow.com/questions/10712002/create-an-empty-list-in-python-with-certain-size) – dustinos3 Nov 07 '18 at 20:22

3 Answers3

1

odds is empty so odds[i] is not going to work. try odds.append(input("...")) instead, which will append the new element to the end of odds

spinodal
  • 670
  • 6
  • 15
0

In the command

odds[i] = input("Enter number ")

you wanted to change the i-th member of the odds list - but such member yet doesn't exist.

Use

odds.append(input("Enter number "))

instead.


Note: And, instead of the construction

while i < x:
    ...
    i = i + 1

you may use more Pythonic way

for __ in range(x):
    ...

without the need of using the variable i. (__ - two underline characters - is a correct Python name used for for never used variables).

So your full code will change to

x = int(input("How many iterations: "))
odds = []
for __ in range(x):
    odds.append(input("Enter number: "))     # Note: you will append strings, not numbers
MarianD
  • 13,096
  • 12
  • 42
  • 54
0

The script tries to reference an entry in the list that doesn't exist. Use append to append. Also you don't need a while loop for this. Corrected code:

x = int(input("How many iterations"))
odds =[]

for i in range(x):
    odds.append(float(input("Enter number: ")))
user8408080
  • 2,428
  • 1
  • 10
  • 19