Python list insert iterators

Thomas Passin list1 at tompassin.net
Fri Mar 3 13:03:35 EST 2023


On 3/3/2023 3:22 AM, Guenther Sohler wrote:
> Hi Python community,
> 
> I have a got an example list like
> 
> 1,  2,  3, 4, 5, 6, 7, 8, 9, 10
>          T               T
> 
> and i  eventually want to insert items in the given locations
> (A shall go between 2 and 3,  B shall go between 6 and 7)
> 
> Right now i just use index numbers to define the place:
> 
> A shall insert in position 2
> B shall insert in position 6
> 
> However when i insert A in position 2, the index for successful insertion
> of B gets wrong
> (should now be 7 instead of 6)
> 
> No, it's not an option to sort the indexes and start inserting from the
> back.
> The most elegant option is not to store indexes, but list iterators, which
> attach to the list element
> and would automatically move, especially if an element is inserted before.
> 
> I could not find such functionality in python lists of [ 1,2,3 ]
> 
> Does python have such functionality ?
> if yes, where can i find it ?

You should be more clear about how to establish the desired insertion 
point.  In your example, you first say that the insertion of B should be 
between 6 and 7. But after A gets inserted, you say that B's insertion 
point should change.  How is anyone able to know what the correct 
insertion point should be at any time?

If the rule is that B should get inserted after a particular known 
element, you can find out the index of that element with list.index() 
and insert just after that. If the rule is "There is an imaginary 
location that starts out after index 6 but moves depending on previous 
insertions", then you will probably need to capture a record of those 
insertions and use it to adjust the invisible insertion point.  But this 
synchronization could be tricky to keep correct depending on what you 
want to do to this list.

So you need to specify clearly what the rules are going to be.


More information about the Python-list mailing list