Вопрос

I have a code I'm studying and I and completely stuck here.

the code is:

def f(*a):
    print a
print (*[1,2]) # prints (1,2)

WHY? I don't know the process behind this. I know that the *args make variable length arguments into tuples, but what does that (*[1,2]) perform?

Это было полезно?

Решение

I think you wanted to write this instead:

print f(*[ 1, 2]) # Python 2
print(f(*[ 1, 2])) # Python 3

What the * does, is something called unpacking. In this case, where you are unpacking a list. It's usually used to pass a list as "independent" parameters to a function, for example:

def f(a, b):
    print a
    print b

You can call it like

f(*[1, 2])  # with unpacking

which is equivalent to

f(1, 2)

Другие советы

This is called argument unpacking - see the reference at the documentation.

In short, print f(*[1,2]) takes each element of the list, and passes it as an individual argument to the method f.

The method f takes a multiple number of positional arguments, which are assigned the name a in the body.

So, when you type f(*[1,2]), this is the same as f(1,2). On the other side, f receives 1,2 as the tuple a and prints it:

>>> def f(*a):
...    print(a)
...
>>> f(*[1,2])
(1, 2)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top