2

I am newbie to Python and I have a doubt regarding insert operation on the list.

Example 1:

mylist = ['a','b','c','d','e']
mylist.insert(len(mylist),'f')
print(mylist)

Output:

['a', 'b', 'c', 'd', 'e', 'f']

Example 2:

mylist = ['a','b','c','d','e']
mylist.insert(10,'f')
print(mylist)

Output:

['a', 'b', 'c', 'd', 'e', 'f']

In second example why it still inserts 'f' element in the list even if I am giving index 10 to insert method?

4
  • 1
    What do you expect the other indexes to contain if it did put 'f' in the 10th index? Commented Aug 3, 2013 at 13:26
  • 1
    @Volatility a not unreasonable assumption would be an error of some sort Commented Aug 3, 2013 at 13:32
  • 1
    I was expecting error. Why it's working that way and not giving any error. Commented Aug 3, 2013 at 13:33
  • @vivekratnaparkhi If you really thing it is wrong, submit a Python Enhancement Proposal. Note: There are no more changes, ever, to existing interfaces in the Python 2.x family. Commented Aug 3, 2013 at 17:53

2 Answers 2

4

The list.insert function will insert before the specified index. Since the list is not that long anyways in your example, it goes on the end. Why not just use list.append if you want to put stuff on the end anyways.

x = ['a']
x.append('b')
print x

Output is

['a', 'b']
Sign up to request clarification or add additional context in comments.

3 Comments

@vivekratnaparkhi : This behaviour is clearly stated in the Python Docs. Quoting - a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
@vivekratnaparkhi If you want the philisophical answer, read up on the principle of least astonishment.
The OP is not talking about using insert to add to the end of a list per se... he expected that trying to insert at a position way past the end of the list might raise an error (probably IndexError). i.e, why should a.insert(len(a), x) be equivalent to a.insert(len(a)+1000000000, x). That, I'm guessing, is where the doubt still lies.
2

The concept here is "insert before the element with this index". To be able to insert at the end, you have to allow the invalid off-the-end index. Since there are no well-defined "off-the-end iterators" or anything in Python, it makes more sense to just allow all indices than to allow one invalid one, but no others.

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.