0

I would like to add an item to a list in python, I want to add the item at an index which is greater than the size of the list. This should cause the list to grow automatically.

For example with a list of 3 items, I would like to insert element at index 6. Is this possible in python without first having to reinitialize the list? It seems Python will merely append to the list if you try to insert an item at index 6 in my example.

4
  • 2
    so what element should be there in index 4 and 5 Commented Oct 8, 2015 at 10:56
  • I am wondering what would be a good use case for that and if it would be how you typically do things in Python. Commented Oct 8, 2015 at 11:00
  • Yes, this is possible - you could subclass list (or MutableSequence) and implement the behaviour you want, for example. Commented Oct 8, 2015 at 11:05
  • Depending what you really want - you could use a dict as a form of sparse list... Commented Oct 8, 2015 at 11:06

1 Answer 1

4

You could write a function which, given a list, an index, and an element, inserts the element in the list before the index if the index is in range (in which case this is equivalent to the built-in insert method) or extends the list by enough Nones to fill it out before tacking it on the end:

>>> def put(xs,i,e):
        n = len(xs)
        if i <= n:
            xs.insert(i,e)
        else:
            xs.extend([None]*(i-n-1))
        xs.append(e)


>>> xs = [1,2,3]
>>> put(xs,6,10)
>>> xs
[1, 2, 3, None, None, 10]
>>> 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.