Converting a varargs tuple to a list - a definite pitfall for new comers to Python
Simon Forman
rogue_pedro at yahoo.com
Fri Sep 15 00:28:52 EDT 2006
metaperl.etc at gmail.com wrote:
> The following program does not work if you uncomment #lis =
> ["xmms2"] + list(args)
>
> Evidently Python is opting for the nullary constructor list() as
> opposed to the other one which takes a sequence. But no newcomer would
> know this. And the Python docs dont give a good example of dealing with
> taking a sequence of args and converting it to a list.
>
> I must've spent 40 minutes looking through my ora books, googling and
> irc'ing in vane on this.
>
> import subprocess
>
> def xmms2(*args):
> #lis = ["xmms2"] + list(args)
> lis = ["xmms2"] + [a for a in args]
> output = subprocess.Popen(lis,
> stdout=subprocess.PIPE).communicate()[0]
> return output.splitlines()
>
> def list():
> lis = xmms2('list')
> playtime_str = lis.pop()
> (total, playtime, time_str) = playtime_str.split()
> (h,m,s) = time_str.split(':')
> lis.pop()
> return dict( playlist = lis, playtime = (int(h), int(m), int(s)) )
>
> if __name__ == '__main__':
> list()
|>> def xmms2(*args):
... lis = ["xmms2"] + list(args)
... return lis
...
|>> xmms2('list')
['xmms2', 'list']
|>>
|>> xmms2('list', 'bananas', 'apples')
['xmms2', 'list', 'bananas', 'apples']
It must be something else?
Also, "nullary"?
More information about the Python-list
mailing list