Jump to content

Python: index out of range


zak100

Recommended Posts

response=  "the following information: Your Course’s Name,"
cnt = 0
matched = []
userInfoToRetrieve = ["Your Professor’s Name", "Your Course’s Name", "Your Course#", "Your id#", "Your Email address"]
for i in range(5):
   print("i= ", i)
   if userInfoToRetrieve[i] in response:
      matched[cnt] = i
      cnt = cnt + 1
      print ("cnt =", cnt)
   if cnt > 0:
        break
print ("cnt = ", cnt)

Hi,

I am getting following error in the above program:

Quote

i=  0
i=  1
Traceback (most recent call last):
  File "/home/zulfi/PycharmProjects/chatbot/searchArr.py", line 10, in <module>
    matched[cnt] = i
IndexError: list assignment index out of range

 

 

Somebody please guide me.

 

Zulfi.

Hi,

I have solved this problem:

matched = np.empty(5)


Zulfi.

Link to comment
Share on other sites

You should use the list.append() method to append an item to the list.

https://www.w3schools.com/python/ref_list_append.asp

list[index] = "data" assigns "data" at the specified index of the list. It must exists in the first place.

Some programming languages allows appendage of element by list[] = "data", but it's not Python.

You don't need to have a 'cnt' variable at all. It's equal to len(list) (the length of the list).

On 12/3/2020 at 5:13 AM, zak100 said:

I have solved this problem:

matched = np.empty(5)

No, you did not. You misunderstood problem (which was clearly stated in your error message i.e. "IndexError: list assignment index out of range "), and used inappropriate for this problem workaround...

You *should* be dynamically appending elements at the end of the list..

Edited by Sensei
Link to comment
Share on other sites

Hi,

Thanks for talking about this. Yes you are right. I used array instead of list and it worked.

 

Following assignment becomes very difficult to handle:

matched = []

and you are right:

Quote

list[index] = "data" assigns "data" at the specified index of the list. It must exists in the first place.

I tried the following and I think it worked:

matched = ["", "", "", "", ""]

and you are saying this:

Quote

You *should* be dynamically appending elements at the end of the list..

This means that if  I use matched.append (i), I don't need the index and I don't have to initialize "matched" by null values as I did above.

Zulfi.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.