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.