Clearing python list with slice operator copy -


i came across following python 2.6 code python

for in elements[:]:     elements.remove(i) 

i'm trying figure out reason use syntax clearing list. understand concept of inplace deletion, why not example:

del elements[:] 

or

elements[:] = [] 

thx !

you must think of python lists 'pointers'.

for example, if declare list so:

elements = [1, 2, 3] 

this seen in memory this:

elements → [ ↓, ↓, ↓ ]              1  2  3 

so when change element in list doing this:

elements[1] = 4                 4 elements → [ ↓, ↑, ↓ ]              1  2  3 

notice how number 2 has no pointer reference 'gone or lost memory' , it's no longer accessible. same happens when re-assign variable itself:

elements[:] = []           [] elements ↑     [ ↓, ↓, ↓ ]                  1  4  3 

the key understand here original list 'gone or lost memory' , it's no longer accessible. important key understand slicing:

elements[:] get's pointer (or arrow in illustrations) variable referring to.

so that's why it's same use

del elements[:] (i delete arrow , set new arrow empty list)

or

elements[:] = [] (i make variable point new empty list, old arrow deleted when dereferenced)

hope helps!


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -