Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python insert() function printing the list the opposite way

[CODE lang="python" title="Insert() function confusion" highlight="3-4"]myList = [] # creating an empty list

for i in range(5):
myList.insert(0, i + 1)

print(myList)[/CODE]

I am new to Python and I am wondering why this outputs the numbers backwards. Surely it starts from 0 and not from the last value?
 
I did not understand. Right now, it starts at 0 or 6? Seems like it should start at 6.

When you give '0' as first argument to 'insert', you insert the value at the start of the array.
Therefore, in the 'for' loop, the array grows like that:
(1)
(2, 1)
(3, 2, 1)
(4, 3, 2, 1)
...
 
In the 'for' loop above, 'i' starts with the value '1' up until 5'.

So, in the first iteration, you insert '1' at the begining of the list.
Then, you insert '2' at the START of the list.
...
Finally, '6' is inserted at the START of the list.

The first argument of 'insert' is the position inside the list where you want to insert the value. If you give '0', then it will be inserted at the beginning of the list.

If you want to add values at the end of the list, use 'append':
myList.append(i)
 
Sorry to bug you with more questions but I am quite curious.

Python:
myList = [] # creating an empty list

for i in range(5):
    myList.insert(2, i + 1)

print(myList)

If I do it this way it outputs

Code:
[1, 2, 5, 4, 3]

Is this because it's just printing every value up until it reaches 5 then the only thing it has left is 2 then 1 so that's why it prints them?
 
Print will simply display the values inside the List, in order. When you give '2' as first argument to 'insert', the value is inserted inside the array at the index 2 from the start of the list. If the list is smaller than 3, then it is inserted at the end.
 
Back
Top Bottom