os.walk walks too much

Marcello Pietrobon teiffel at attglobal.net
Fri Feb 27 14:51:04 EST 2004


Hi Steve,

Steve Lamb wrote:

>On 2004-02-25, Peter Otten <__peter__ at web.de> wrote:
>  
>
>>dirs[:] makes a slice containing all elements, i. e. a shallow copy of the
>>complete list, so the loop is not affected by changes to the original:
>>    
>>
>
>  
>
>>>>>dirs = ["alpha", "beta", "gamma"]
>>>>>dirs == dirs[:] # equal
>>>>>          
>>>>>
>>True
>>    
>>
>>>>>dirs is dirs[:] # but not the same list
>>>>>          
>>>>>
>>False
>>    
>>
>
>    Better way to make it crystal clear.
>
>{grey at teleute:~} python
>Python 2.3.3 (#2, Jan 13 2004, 00:47:05)
>[GCC 3.3.3 20040110 (prerelease) (Debian)] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
>  
>
>>>>real = [1, 2, 3]
>>>>copy = real[:]
>>>>real
>>>>        
>>>>
>[1, 2, 3]
>  
>
>>>>copy
>>>>        
>>>>
>[1, 2, 3]
>  
>
>>>>for x in real:
>>>>        
>>>>
>...     print(x)
>...     real.remove(x)
>...
>1
>3
>  
>
>>>>real
>>>>        
>>>>
>[2]
>  
>
>>>>real = [1, 2, 3]
>>>>for x in real[:]: # IE, same as using copy
>>>>        
>>>>
>...     print(x)
>...     real.remove(x)
>...
>1
>2
>3
>  
>
>>>>real
>>>>        
>>>>
>[]
>
>    To the original poster, the reason changing the list you're iterating over
>is because the index doesn't move along with the data in it.  So in the first
>loop 1 and 3 are printed, 2 is left.  Why?  Assign indexes do the data.  This
>is most likely not how Python does it internally but this is good to show what
>happened.
>
>[1, 2, 3]
> 0  1  2
>
>    First run through x is one but it got it from the first index, 0.  So x is
>1.  Then you remove 1 from the data set so now it looks like this.
>
>[2, 3]
> 0  1
>
>    So now Python moves on in the loop, it grabs the next index which is 1.
>However, since you've changed the list that index now points to 3, not 2.  It
>grabs 3, prints it then removes it.  So now we're left with:
>
>[2]
> 0
>
>    Since it's already done 0 the loop ends.  By using a copy you're using the
>copy to preserve the indexing to the data while you manipulate the data.  Hope
>this clears it up.  :)
>
>
>  
>

I thought intuitively something like that, but your help has been... 
helpful ! :)

Can I ask you one more thing ?

It is surprizing to me that in

for x in real[:]

dirs[:] creates a copy of dirs

while

dirs[:] = [] - empty the original list
and
dirs = [] - empty a copy of the original list

I understand ( I think ) the concept of slicing, but this is stil 
surprizing to me.
Like to say that when I do

for x in real[:]

this is not using slicing

While
dirs[:] = []
is using slicing


Maybe I just making a big mess in my mind.
It looks like assignments in Python and C++ are pretty different


Cheers,
Marcello








More information about the Python-list mailing list