Python | Add the element in the list with help of indexing

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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]))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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]))

chevron_right


Output :

The inserted element is : 24


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.