Insert Method for Lists

Hi. A Python newbie here. I like to ask how did the below code produce numbers in reverse?
I don’t see a reverse method, so how come it resulted to [5,4,3,2,1]?
Thank you.

</>
my_list = [ ]
for i in range (5):
my_list.insert (0, i + 1)
print (my_list)
</>

[5, 4, 3, 2, 1]

Thank you.

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.

1 Like

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.

Thank you for the explanation!

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.

For details, see the documentation:

1 Like

Hey @Moonlight001

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 :slight_smile: Try this out:

>>> def fun(a, lis=[]):
           lis.append(a)
           return lis
>>> fun(42)
[42]
>>> fun(42)
[42, 42]    # isn't the default list lis empty?
>>> fun(3, [])
[3]  # as expected
>>> fun(4, [])
[4]  # ok, still as expected
>>> fun(5)
[42, 42, 5]  # wth?! :)~

Thank you.

I will get back to this when I reach the “function” topic :)) But yeah it seems puzzling…

explanation plz? : )

@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:

  1. 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.
  2. 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.
  3. 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… :slight_smile: (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).

Please see:

Thank you for the help!

Also a newbie, I have a similar question. If the example were:
my_list =
for i in range (5):
my_list.insert (3, i + 1)
print (my_list)

i + 1 = 1 at index 3, 1 + 1 = 2 insert at index 3… and so through range 5
wouldn’t the output be [5, 4, 3, 2, 1] at indices 3, 4, 5, 6, 7 respectively? For whatever reason I don’t understand why the output is [1, 2, 3, 5, 4]

Try printing my_list on each iteration, it will help you understand what is happening. To start off, you are trying to insert at position 3 for every insert, but in the first three iterations, there is no insertion point 3, so [1, 2, 3] all get inserted in order. After those, you insert 4 in position 3 ([1, 2, 3, 4]) and then 5 at position 3 ([1, 2, 3, 5, 4]).

thank you. that seems so obvious now. much appreciated.

@Moonlight001 If you want [1, 2, 3, 4, 5], you can simply do:

list(range(1,6))