os.walk walks too much

Steve Lamb grey at despair.dmiyu.org
Fri Feb 27 23:32:25 CET 2004

```On 2004-02-27, Marcello Pietrobon <teiffel at attglobal.net> wrote:
> Can I ask you one more thing ?

Sure.  However I am a Python neophyte who happens to have a few years
experience so take everything I say with a large heaping of salt.  :)

> It is surprizing to me that in

Ah, took me a minote to see what you were saying.

> for x in real[:]

> dirs[:] creates a copy of dirs

Well, creating a copy is the shorthand.  What both of these are doing is
"output the values from the array x from y to z."  Since y and z are not
specified you get the whole array (or string, or directory or any other
slicable object).

> while

> dirs[:] = [] - empty the original list

This is "assign the range of x to y the list given".  A better way to see
it would be to do this:

= [1, 2, 3, 4]
>>> foo
[1, 2, 3, 4]
>>> foo[1:2] = [3, 2, 5]
>>> foo
[1, 3, 2, 5, 3, 4]

Hmmm, ok, even I'm scratching my head at that since I expected 1, 3, 2, 5
4.  Erm, but you get the idea.  :)

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

This is because here you're assigning the name to a new object.

So in order...

for x in real[:] - iterate over the results of the slice of real from y to z.

foo = dirs[:] - Assign foo to the results of the slice of dirs from y to z.

dirs[:] = [] - Assign the the area of dirs defined by slice y to z with an
emptry array.

dirs = [] - Assign the name dirs to a new, empty array.

Where most people get hung up is the different between strings, which are
immutable, and lists/dictionaries, etc. which are mutable.  :)

> 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

Yes, it is.  Take foo from above...

>>> id(foo)
1075943980
foo points to object 1075943980.

>>> id(foo)
1075943980
foo still points to object 1075943980.

>>> id(foo[:])
1075943308
However this is a different object, 1075943308.

So in the above example it is using a slice.  real[:] is returning a slice
and it is that object which x is iterating over.  Just because that slice
doesn't have a name assigned to it doesn't mean it doesn't exist.  :)

> While
> dirs[:] = []
> is using slicing

Well, it is using it in a different manner.  Above you're using slicing to
tell Python what to return.  Here you're using slicing to tell Python what to
replace.

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

Never touched C++ so I cannot say.  :)

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

```