Hope you are doing well,
I was working on lists (string list) and realised that python uses INSERTING BEFORE option but I personally found INSERTING AT as the most intuitive one.
Which one of the 3 behaviours do you prefer (based on your own terms) from insert function for lists:
- INSERTING AFTER: Insert the new element after ( i )-th index
- INSERTING BEFORE: Insert the new element before ( i )-th index
- INSERTING AT: Insert the new element at ( i )-th index, so that after insertion is done newly added element is at ( i )-th index [irrespective of ( i ) being a forward or backward index]
0 voters
Please Note: There is NO difference between INSERTING BEFORE and INSERTING AT when it comes to forward indexes.
Similarly, there is NO difference between INSERTING AFTER and INSERTING AT when it comes to backward indexes.
let’s take an example:
list = [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ] (I am considering 1 based indexing in both forward and backward directions here i.e. first element is at index 1 and last element is at index -1)
Inserting at FORWARD index 3
insert_after( list, index = 3, new_element = ‘new element’ )
—> [ ‘a’, ‘b’, ‘c’, ‘new element’, ‘d’, ‘e’ ]
insert_before( list, index = 3, new_element = ‘new element’ )
—> [ ‘a’, ‘b’, ‘new element’, ‘c’, ‘d’, ‘e’ ]
insert_at( list, index = 3, new_element = ‘new element’ )
—> [ ‘a’, ‘b’, ‘new element’, ‘c’, ‘d’, ‘e’ ]
Inserting at BACKWARD index 2
insert_after ( list, index = -2, new_element = ‘new element’ )
—> [ ‘a’, ‘b’, ‘c’, ‘d’, ‘new element’, ‘e’ ]
insert_before ( list, index = -2, new_element = ‘new element’ )
—> [ ‘a’, ‘b’, ‘c’, ‘new element’, ‘d’, ‘e’ ]
insert_at ( list, index = -2, new_element = ‘new element’ )
—> [ ‘a’, ‘b’, ‘c’, ‘d’, ‘new element’, ‘e’ ]