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
Recommended Posts:
- Python | Replace elements in second list with index of same element in first list
- Python | Subtract two list elements if element in first list is greater
- Python | Indices list of matching element from other list
- Python | Insert Nth element to Kth element in other list
- Python | Slicing list from Kth element to last element
- Python | Move one list element to another list
- Indexing in MongoDB using Python
- Python | Indexing a sublist
- Python | Every Kth element in list
- Python | Three element sum in list
- Python | How to get the last element of list
- Python - Remove first element of list
- Python - Sum of each List element occurrence in another
- Python | Element repetition in list
- Python | Equidistant element list
- Python | Operation to each element in list
- Python | Operate on every Kth element of list
- Python | Last occurrence of some element in a list
- Python | Top N pairs by Kth element from list
- Python | Insert after every Nth element in a list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

