Because during each iteration you keep inserting the new number at the beginning of the list (index 0).
If you are generating numbers 1 - 5, but keep inserting the next number before the previous, you end up with the numbers in reverse order. If you want them in the order you generate them, just use my_list.append(i + 1) instead of inserting at the start.
Oh, I see. I get it now. I shouldn’t have thought of [1,2,3,4,5] at first…and then inserting into the front each time (if i make sense hehe). Should have been one by one… with each new number in front of the previous.
Every time that a value was inserted, it was inserted at the beginning of the list. Of course that will reverse the values; why is this surprising? Similarly you may notice that if you take a deck of cards and put the top card onto the table, then the next card on top of that, etc., you end up reversing the cards.
Or is the question about what my_list.insert(0, i + 1) means? This says that the result i+1 will be inserted, at position 0 of the list - that is to say, before any values that were already there.
Lists can sometimes be tricky. Here is a fun kind of puzzle (which has nothing to do with your question), but is a puzzle that every Python beginner should consider at one point or another Try this out:
>>> def fun(a, lis=):
[42, 42] # isn't the default list lis empty?
>>> fun(3, )
 # as expected
>>> fun(4, )
 # ok, still as expected
[42, 42, 5] # wth?! :)~
@Eyalvr12 ChatGPT (3.5) is not always reliable, but it can explain this. A mutable object is used as default argument. Python creates that object only once, when the function is defined. So, it creates a shared state.
Quoting from ChatGPT (to save myself some typing):
Here’s a step-by-step explanation of how this shared state works and why it can lead to unexpected behavior:
Function Definition: When you define the function, Python evaluates the default argument and creates a list object. This object is associated with the function definition, not with any specific function call.
Shared Object: Subsequent calls to the function that do not provide a value for the argument will use the same default list object. This means that all these calls are operating on the same list in memory.
Accumulation of State: If the function modifies the default list (e.g., appends elements to it), those modifications accumulate across multiple calls because they are acting on the same shared list object.
So, that’s why you should basically never use lists or dicts or other mutable objects as default arguments… (unless you explicitly want to make use of that shared state of course - but I’ve never seen examples of that; I have seen plenty of cases, on the other hand, where the default empty list or dict caused unexpected behavior).