determining the number of output arguments
Jeff Shannon
jeff at ccvcorp.com
Mon Nov 15 16:32:29 EST 2004
Darren Dale wrote:
>Hello,
>
>def test(data):
>
> i = ? This is the line I have trouble with
>
> if i==1: return data
> else: return data[:i]
>
>a,b,c,d = test([1,2,3,4])
>
>How can I set i based on the number of output arguments defined in
>(a,b,c,d)?
>
>
Something like this:
def test(*args, **kwargs):
i = len(args) + len(kwargs)
should work. But note that the usage example you gave will result in i
having a value of 1 -- you're passing in a single argument (which is a
list).
Of course, if you're always going to be passing a sequence into your
function, and you want to get the length of that sequence, then it's
pretty simple:
def test(data):
i = len(data)
return data[:i]
Note, however, that this function is effectively a no-op as it stands.
Presumably you're intending to do something to transform data, which may
change its length? Otherwise, it would be simpler to just modify the
list (or a copy of it) in-place in a for loop / list comp, and not worry
about the length at all.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list