Search code examples
pythonlistinsertappendextend

A way to insert a value in an empty List in a specific index


Is there a way to insert a specific value into a List into a specific index. List should be completely empty:

L = []
L.insert(2,177)
print(L)

L should give out the values of L [ , ,117].


Solution

  • That is not possible. Lists cannot have "holes"; every slot in the list must contain a value.

    You have two options:

    1. Fill the list with dummy values:

      L = [None] * 3
      L[2] = 177
      # L: [None, None, 177]
      
    2. Use a dict rather than a list:

      L = {}
      L[2] = 177
      # L: {2: 177}
      

      A dict is a mapping between arbitrary values, so it can handle "holes" with no problem.