List Insert() returns Argument is out of range

I have an empty GameObject list, and when I try to add items to it using Insert(), i get an error saying:
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index

public class Box : MonoBehaviour {

	protected List<GameObject> Items;

	void Start () {
		weapons = new List<GameObject>();
	}
	

	public void addItem(GameObject item){
			ItemBase item_base = item.GetComponent<ItemBase>();
			items.Insert(item_base.item_id, item);
		}
	}
}

the item_base.item_id is an int. What am I doing wrong?

The List collection doesn’t let you have spaces, so if I was to do something like:

List<string> myList = new List<string>();
myList.Insert(9, "Derp");

This isn’t going to work because the list currently has a size of zero. This also applies to:

List<string> myList = new List<string>();
myList.Insert(0, "Derp");

I think what you’re looking for is a dictionary:

Dictionary<int, GameOject> items = new Dictionary<int, GameOject>();
items[item_id] = item;

When using List(t).Insert(int index, T item), the first argument is supposed to be an index to insert the element at, but it has to fit within the current size of the list. The value you use must be greater or equal to 0 AND less or equal to List.Count.

Therefore your item ids may not fit this requirement.

You can use List.Add, then the new element will always end up at the end of the list and it will resize appropriately.

If that is for some reason not suitable, you may need to give more details of what do you want to achieve.