should os.walk return a list instead of a tuple?

bruno at modulix onurb at xiludom.gro
Tue Mar 21 06:17:13 EST 2006


Ministeyr wrote:
> Hello,
> 
> os.walk doc: http://www.python.org/doc/2.4/lib/os-file-dir.html#l2h-1625
> 
> When walking top to bottom, it allows you to choose the directories you
> want to visit dynamically by changing the second parameter of the tuple
> (a list of directories). However, since it is a tuple, you cannot use
> "filter" on it, since it would mean reassigning it:
> 
> for dir_tuple in os.walk('/home'):
>     dir_tuple[1]=filter(lambda x: not x.startswith('.'),
> dir_tuple[1])         #do not show hidden files
>     print dir_tuple        #just print the directory and its contents in
> the simplest possible way

Ok, you are missing 2 points here :
1/ multiple assignment. Python allows you to do things like:
a, b, c = (1, 2, 3)

So the canonical use of os.walk is:
for dirpath, subdirs, files in os.walk(path):
  ...

2/ what's mutable and what is not: a tuple is immutable, but a list is
not. The fact that the list is actually an element of a tuple doesn't
make it immutable:

>>> t = ('A', [1, 2, 3])
>>> t
('A', [1, 2, 3])
>>> t[1]
[1, 2, 3]
>>> # this will work
>>> t[1].append(4)
>>> t
('A', [1, 2, 3, 4])
>>> # this won't work
>>> t[1] = []
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
>>>

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list