ignoring a part of returned tuples

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Jul 4 10:29:47 CEST 2007


noamtm a écrit :
> Hi,
> 
> Some functions, like os.walk(), return multiple items packed as a
> tuple:
> 
> for (dirpath, dirnames, filenames) in os.walk(...):
> 
> Now, if you don't care about one of the tuple members, is there a
> clean way to ignore it,

Yes : just ignore it !-)

> in a way that no unused variable is being
> created?

the term 'variable' in Python can be somewhat misleading. You have 
objects, and you have names bound to objects. In your case, whether you 
bind it to a name or not, the object will be created, so it wont make 
much differences.

> What I wanted is:
> for (dirpath, , filenames) in os.walk(...):
> 
> But that doesn't work.

A common idiom is to use '_' for unused values, ie:

for (dirpath, _, filenames) in os.walk(...):

You could also just bind the whole tuple to a ssinngle name then 
subscript it:

for infos in os.walk(...):
   # now dirpath is infos[0] and filenames is infos[2]

but this won't buy you much...



More information about the Python-list mailing list