Search code examples
pythonfunctioninsert

insert() function with items in reverse order


I'm new to python and want to learn everything about it. There's something I don't understand for the following given code snippet:

list = []
for i in range(5):
    list.insert(0,i+1)
print(list)

Why does insert(0, i+1) gives the same output as append(i+1), but in the reverse order? I don't understand the syntax / reason behind using just a 0 separated by a comma. Every idea is welcome!

Edit: I don't see any difference between the append method, which inserts 0 1 2 3 4 5 at the end of the list and insert(0,i+1), which inserts the same thing at the start of the list. The list is empty, how does it come, that they are in reverse order ?


Solution

  • The python documentation explains this https://docs.python.org/3/tutorial/datastructures.html?highlight=insert

    In any case this ( https://docs.python.org/3/ ) is a good place to search, though sometimes searching in stack overflow might return an easy to understand faster

    list.insert(pos, val) inserts the value val before position pos

    inserting before position 0 means, the element to insert will be the first element of the list.

    whereas a.append(x) (which is equivalent to a.insert(len(a), x)) appends the new element at the end of the list.

    Therefore the order is reversed.