Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 26 Jan, 2019

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




# 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



My Personal Notes arrow_drop_up
Recommended Articles
Page :