Python, question about tuples and args


#1

i was following some tutorial and came across this:

print(*(0,1))

which will output:

0 1

in simply terms, has it something to do with *args? I found some documentation about it:

https://docs.python.org/dev/reference/expressions.html#calls

But to be honest, it actually got more confused then getting an answer.

Now i don't have a question, how come the output is 0 1, is this because it prints the separate arguments?


#2

The following executes in Python 3, since we are using print as a function.

The * scatters the items in the tuple into separate arguments. Accordingly, this ...

print(*(0,1))

... becomes ...

print(0,1)

This ...

x = (i ** 2 for i in range(11))
print(*x)

... outputs this ...

0 1 4 9 16 25 36 49 64 81 100

#3

yea, i thought so it wouldn't work for python2 because in python2 print is not yet a function.

one final question, the scattering happens before the function is called? It seems to be the case:

def example(x):
  print(x)
example(*(0,1))

Thank you for your help, always nice to learn new things :slight_smile:


#4

We can also use ** to scatter a dict into named or keyword arguments.

The following scatters (EDIT: unpacks; see @ionatan below) vals into named arguments.

# scatter a dict into named arguments

# polynomial function to receive arguments
def polynomial(a, b, c, x):
    return a * x ** 2 + b * x + c

# the vals dict will be scattered
vals = {"a": 2, "b": -7, "c": 3}

# iterate to assign values to x
for x in range(11):
    vals["x"] = x
    # scatter vals into named arguments
    print(x, polynomial(**vals))

Output:

0 3
1 -2
2 -3
3 0
4 7
5 18
6 33
7 52
8 75
9 102
10 133

#5

Docs, PEPs etc refer to it as unpacking

https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

There's something similar with assignment as well

for i, v in enumerate(my_values):
    ....

a, b = b, a

a, (b, c,), d = (1, (2, 3), 4)

a, b, *rest = 1, 2, 3, 4

#6

i will take some time to read through this and play with all the code samples, it seems there is always more to learn


#7

See the following from Think Python, 2nd Edition by Allen B. Downey for additional examples: