lisp - What does the asterisk do in Python other than multiplication and exponentiation? -


this question has answer here:

in peter norvig's lisp interpreter written in python (http://norvig.com/lispy.html), defines lisp's eval follows:

def eval(x, env=global_env):     "evaluate expression in environment."     if isa(x, symbol):             # variable reference         return env.find(x)[x]     elif not isa(x, list):         # constant literal         return x                     elif x[0] == 'quote':          # (quote exp)         (_, exp) = x         return exp     elif x[0] == 'if':             # (if test conseq alt)         (_, test, conseq, alt) = x         return eval((conseq if eval(test, env) else alt), env)     elif x[0] == 'set!':           # (set! var exp)         (_, var, exp) = x         env.find(var)[var] = eval(exp, env)     elif x[0] == 'define':         # (define var exp)         (_, var, exp) = x         env[var] = eval(exp, env)     elif x[0] == 'lambda':         # (lambda (var*) exp)         (_, vars, exp) = x         return lambda *args: eval(exp, env(vars, args, env))     elif x[0] == 'begin':          # (begin exp*)         exp in x[1:]:             val = eval(exp, env)         return val     else:                          # (proc exp*)         exps = [eval(exp, env) exp in x]         proc = exps.pop(0)         return proc(*exps)  isa = isinstance  symbol = str 

this line in particular interests me:

return proc(*exps) 

what asterisk in of exps doing exactly?

single asterisk in before seqable object unpacks it, joran showed:

in [1]: def f(*args): return args  in [2]: f(1,2,3) out[2]: (1, 2, 3)  in [3]: f(*[1,2,3,4]) out[3]: (1, 2, 3, 4) 

(note third application *: in function definition asterisk indicates variable length list of arguments, being packed 1 list, args, in in [1])

also worth noting double asterisk (**) dictionary unpacking:

in [5]: def g(foo=none, bar=42): return foo,bar  in [6]: g() out[6]: (none, 42)  in [7]: g(*[1,2]) out[7]: (1, 2)  in [8]: g(**{'foo': 'foo', 'bar': 'bar'}) out[8]: ('foo', 'bar') 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -