demo = []
for i in range(1,11):
demo.insert(-1,i)
print(demo)
the result is [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
demo = []
for i in range(1,11):
demo.insert(0,i)
print(demo)
the result is [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
The former code block is used to realize something like append(). Obviously, something went wrong. However, when I changed the index from -1 to 0, just as the latter code block, it seems all right. I'm confused about that.
CodePudding user response:
-1
refers to the position of the last element, but you don't actually want to insert your elements there. You want to insert at the position after the last element, not the position of the last element.
If you want to do that with insert
, you need to insert at index len(demo)
. You cannot use a negative index to accomplish this.
CodePudding user response:
From the python docs:
a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x)
side note: a more pythonic approach might use list comprehensions, so if you're not familiar with the concept, take a look.