Вопрос

So I'm trying to understand how the use of * in the lambda example below fits within the *arg/**kwarg Python idioms.

If I create a simple function, summing, that uses sum(iterable) to sum a list of numbers, there's at least a couple ways to do it.

def summing(*x): return sum(*x)

or I've seen other code which uses this version for lambda

summing = lambda * x: sum(*x)

For the lambda version, I don't really understand how the * symbol fits into the idiom. I'm assuming that it's not meant to be a glob pattern -- so what is it? Is it used elsewhere in Python? (Or is something like "*args" whitespace insensitive?)

(This question started with a little snippet of code that stumped me.)

Это было полезно?

Решение

summing = lambda *x: sum(*x)

is basically the same as

def summing(*x): return sum(*x)

but functions are prefered, as they are more readable and a bit faster.

However, you shouldn't use either of the above code snippets. *x allows for a variable amount of arguments, only to unpack them for sum().

If you want to pass your summing() function arguments like this:

summing(1,2,3,4)

... use the following code:

def summing(*x): return sum(x)

If you want to give it a sequence instead...

summing([1,2,3,4])

... use this:

def summing(x): return sum(x)

Your variant...

def summing(*x): return sum(*x)

... requires a sequence to be passed (like the function above, hence you don't need *x twice!), you can't give it (1,2,3,4). sum() takes an iterable as first argument, the second is for a start value. sum(*x) will throw errors at you.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top