for loop specifying the amount of vars

Tim Chase python.list at tim.thechases.com
Mon Nov 24 14:39:22 EST 2008


> I have a list which contains a folder structure, for instance:
> 
> dirs=['c:\', 'temp', 'foo', 'bar']
> 
> The length of the list can vary. I'd like to be able to construct a
> os.path.join on the list, but as the list can vary in length I'm unsure how
> to do this neatly. 

Sounds like you want argument unpacking:

   >>> dirs=['c:\\', 'temp', 'foo', 'bar']
   >>> print os.path.join(*dirs)
   c:\temp\foo\bar

(side note:  you can't have a single trailing backslash like your 
example assignment)

The asterisk instructs python to unpack the passed list as if 
each one was a positional argument.  You may occasionally see 
function definitions of the same form:

   def foo(*args):
     for arg in args:
       print arg
   foo('hello')
   foo('hello', 'world')
   lst = ['hello', 'world']
   foo(*lst)

You can use "**" for dictionary/keyword arguments as well.  Much 
more to be read at [1].

-tkc


[1]
http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html





More information about the Python-list mailing list