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

Question:

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].

Asked By: user9935508

||

Answers:

iterables in Python must have objects inside. You can fill the list with None up to the place you want your actual value

l = [None for _ in range(200)]
l[2] = 2
l[177] = 177

None

The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.

Answered By: CIsForCookies

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.

Answered By: Aran-Fey
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.