0

Before Anything this is my first time asking a question here so if there's Something wrong with the format of the question I'm sorry about that.

So basically This is a code that is supposed to get a list of numbers, and a number from user and check to see if the second input is equal to any of the elements of the list, then put those element index numbers in a new list and print it.

The thing is the error is saying 'a' is not defined but if I define it before the for loop like this:

a=[]

or

a=list()

I get this:

a[k]= c
IndexError: list assignment index out of range 

Here's the code:

x = eval(input('list'))
y = eval(input('number'))
k=0
c=0
for i in x:
    if y==i:
        a[k]= c
        k+=1
    c+=1
print(a)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
P.33
  • 1
  • 4
    Possible duplicate of [IndexError: list assignment index out of range](https://stackoverflow.com/questions/5653533/indexerror-list-assignment-index-out-of-range) – Patrick Haugh Apr 23 '19 at 17:25
  • 1
    Are you wanting to just `append` to `a`? You can't assign to arbitrary indices that don't already have an element. – Carcigenicate Apr 23 '19 at 17:25
  • Of course, the variable `a` *must be defined before you use it*. The issue here is that when you index into a list, your index must be in-bounds. If you want to *add an element to the list*, you should use an appropriate mutator method, in this case, `.append` – juanpa.arrivillaga Apr 23 '19 at 17:29
  • @ Carcigenicate yes I was, for some reason didn't think of appending it. – P.33 Apr 23 '19 at 17:47
  • @ juanpa.arrivillaga thanks that does it. – P.33 Apr 23 '19 at 17:48

2 Answers2

0

A list in python doesn't support index assignment. - Therefore the indices will always be numeric depending on the position 0, 1, n.

To add use append, to have a hash map use a dict.

Julian Camilleri
  • 2,975
  • 1
  • 25
  • 34
0

Instead of

a[k]= c

You can use

a.append(c)
veekaly
  • 240
  • 3
  • 9