Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why *args doesn't work with string formatting

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.

like image 832
d.putto Avatar asked Nov 29 '25 09:11

d.putto


1 Answers

*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)