os.walk walks too much

Steve Lamb grey at despair.dmiyu.org
Wed Feb 25 21:41:15 EST 2004


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.  :)


-- 
         Steve C. Lamb         | I'm your priest, I'm your shrink, I'm your
       PGP Key: 8B6E99C5       | main connection to the switchboard of souls.
-------------------------------+---------------------------------------------



More information about the Python-list mailing list