One can easily add elements to the list using the append functions. But in competitive programming, we might need to memoize sometimes, hence we need to add the element in the list with help of indexing, that is, fill the later index before population previous indices. Performing this in normal circumstances outputs an error as no memory is allocated beforehand to list. Let’s discuss certain ways in which this can be performed.
Method #1 : Using Pre Initialization with None
The solution to this problem can come by the fact that if we initialize all the elements with None, the memory will get allocated to the list and then it can be overridden later as required.
# Python3 code to demonstrate # indexing element in list # pre initializing with None # initializing list test_list = [None] * 50 # assigning value test_list[5] = 24 # printing inserted element print ("The inserted element is : " + str(test_list[5]))
Output :
The inserted element is : 24
Method #2 : Using dictionary
This technique doesn’t necessarily create the list but rather created the dictionary which can, in turn, be used in the place of list and can perform the similar task of indexing. This method is just the hack over the problem mentioned.
# Python3 code to demonstrate # indexing element in list # using dictionary # initializing list test_list = {} # assigning value test_list[5] = 24 # printing inserted element print ("The inserted element is : " + str(test_list[5]))
Output :
The inserted element is : 24