-->

Confusion in understanding tuple and *args in Pyth

2019-02-25 23:22发布

问题:

I need a function which would be taking variadic arguments. The number of arguments may vary from 1 to N.

def abc(*args):
    print "ABC"
    print args
    print len(args)

def abc1(*args):
    print "ABC1"
    print args
    print len(args)
    print "------------"


tup = ("Hello123")
abc(*tup)
abc1(tup)
tup = ("Hello123", "Hello1234")
abc(*tup)
abc1(tup)

The ouput of the above program is;

ABC
('H', 'e', 'l', 'l', 'o', '1', '2', '3')
8
ABC1
('Hello123',)
1
------------
ABC
('Hello123', 'Hello1234')
2
ABC1
(('Hello123', 'Hello1234'),)
1
------------

If I look into this output,when i am passing only 1 argument in abc1(), the length of tuple becomes 8(keeping *tup), where as in the abc1() it shows the length is 1. why and how? But the same is not working differently when I am passing 2 arguments in the code above. The output comes as tuple and tuple of tuple. How to resolve this problem because I have to write the code which will work for all N

回答1:

Parentheses don't make tuples, commas do. To build a single-element tuple, the correct syntax is

tup = ("Hello123",)  # parentheses are optional but help readability

which is equivalent to

tup = "Hello123",

Remember that you can write

x, y = y, x  # swaps x and y using tuple packing/unpacking

just as well as

(x, y) = (y, x)

The only exception where parentheses are mandatory is the empty tuple ().