Number_input variable result in: IndexError: list index out of range

If I define a value to item_id variable, the system will work perfectly. But, if I use number_input (or text input), doesn’t work:

item_id = 3 (this will work in the system)

item_id = int(st.number_input("Enter the book id: ")) -> (this gives me the error: list index out of range)

This is the part of the code:

			elif task == "Recommendation":
				if st.button('Ask Recommendation'):
					for idx, row in ds.iterrows():
						similar_indices = cosine_similarities[idx].argsort()[:-100:-1]
						similar_items = [(cosine_similarities[idx][i], ds['id'][i]) for i in similar_indices]

						results[row['id']] = similar_items[1:]

					def item(id):
						return ds.loc[ds['id'] == id]['description'].tolist()[0].split(' - ')[0]

					item_id = int(st.number_input("Enter the book id: "))

					def recommend(num):
						st.text("Recommending" + str(num) + " a similar book to " + item(item_id) + "...")
						st.text("-------")
						st.text("-------")
						st.text("-------")
						recs = results[item_id][:num]
						for rec in recs:
							st.text("Recommend: " + item(rec[1]))
					recommend(num=1)

Hi @erarich, Welcome to the community !

The error is coming because results does not have the index you are looking for,

You can try st.write(len(results), item_id) to debug if your results list’s length > item_id. I’d suggest giving an upper and lower bound to your number input if you are using the value for indexing a list.

The IndexError is raised when attempting to retrieve an index from a sequence (e.g. list, tuple), and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:

Raised when a sequence subscript is out of range.

Here’s an Python Split() example that raises the IndexError:

data = "one%two%three%four%five"
numbers = data.split('%')

The list numbers has 5 elements, and the indexing starts with 0, so, the last element will have index 4. If you try to subscript with an index higher than 4, the Python Interpreter will raise an IndexError since there is no element at such index.