-1

I was writing a function to find the number of unique words from input.

At a moment when i was bored and try to do nothing to kill time, I wished to print all words that was passed to the function via *arg.

It is known that *args was a tuple, so the code

print(arg)

was supposed to out put "('babe', 'I', 'love', 'you')" or "('babe', 'I', 'love', 'you', 'do', 'you', 'love', 'me')", and I knew that.

However, there is a typo in my code, a unexpected "*". So the code is actually:

print(*arg)

why it work, why didn't it raise an exception? None of Google , Baidu nor Bing had the answer.

enter image description here

Elias
  • 49
  • 3

1 Answers1

0

Using *a instead of a in general throws an error, because they are different. *a in a function call foo(*a) would be equivalent to foo(a[0], a[1], ...), i.e., pass each element of a as a separate argument. This is called "unpacking." On the other hand, foo(a) would pass the whole iterable a as a single argument to foo.

But why didn't your case throw an error? It's because print also accepts multiple arguments, and then print each argument delimited by a blank (by default):

a = ('hello', 'world')

print(a) # ('hello', 'world')
print(*a) # hello world
print('hello', 'world') # hello world

In this example the second and the third lines of print are the same; print(*a) is equivalent to print(a[0], a[1]) which is print('hello', 'world').

In contrast, the first one is different. In that case, you are giving a tuple to print, so that it prints the string representation, "('hello', 'world')" of that tuple.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • And implicit in the previous answer. `*x` is allowed as an argument to a python function. It just means that x is sequence-like, and that the values of that sequence should be inserted as arguments. `foo('a', *range(5), 'b')` is the same as `foo('a', 0, 1, 2, 3, 4, 'b')`. – Frank Yellin Oct 17 '21 at 05:33
  • @FrankYellin Yes, and actually unpacking has been generalized further; for example, you can now do something like `x = [2, 3, 4]; lst = [1, *x]`. https://www.python.org/dev/peps/pep-0448/. – j1-lee Oct 17 '21 at 05:35