Jump to content

Python: index out of range

Featured Replies

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.

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

  • Author

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.

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.