I am trying to understand Python *args and **kwargs operates. Let's consider a function which takes 4 arguments. We can pass list x as argument to function using *x
def foo(a,b,c,d):
print a,b,c,d
x=[1,2,3,4]
foo(x)
#TypeError: foo() takes exactly 4 arguments (1 given)
foo(*x)
#1 2 3 4 # works fine
print "%d %d %d %d" %(*x)
#SyntaxError: invalid syntax
if I got it correct, in case foo() *x unpacks values...then why error in case of print "%d %d %d %d" %(*x) ??
Note- I am not interested in how to print a list in one line but just curious why print "%d %d %d %d" %(*x) not works.
*x unpacks the contents of x into arguments, as opposed to a tuple; and a tuple is what % should be passed.
print "%d %d %d %d" % tuple(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With