Confusion in understanding tuple and *args in Python

我的未来我决定 提交于 2019-12-20 03:09:58

问题


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 ().



来源:https://stackoverflow.com/questions/35326330/confusion-in-understanding-tuple-and-args-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!