Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

Python parameter list with single argument

When testing Python parameter list with a single argument, I found some weird behavior with print.

>>> def hi(*x):
...     print(x)
...
>>> hi()
()
>>> hi(1,2)
(1, 2)
>>> hi(1)
(1,)

Could any one explain to me what the last comma mean in hi(1)'s result (i.e. (1,))

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually the behavior is only a little bit "weird." :-)

Your parameter x is prefixed with a star, which means all the arguments you pass to the function will be "rolled up" into a single tuple, and x will be that tuple.

The value (1,) is the way Python writes a tuple of one value, to contrast it with (1), which would be the number 1.

Here is a more general case:

def f(x, *y):
    return "x is {} and y is {}".format(x, y)

Here are some runs:

>>> f(1)
'x is 1 and y is ()'
>>> f(1, 2)
'x is 1 and y is (2,)'   
>>> f(1, 2, 3)
'x is 1 and y is (2, 3)'
>>> f(1, 2, 3, 4)
'x is 1 and y is (2, 3, 4)'

Notice how the first argument goes to x and all subsequent arguments are packed into the tuple y. You might just have found the way Python represents tuples with 0 or 1 components a little weird, but it makes sense when you realize that (1) has to be a number and so there has to be some way to represent a single-element tuple. Python just uses the trailing comma as a convention, that's all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...