Ammar Khazal Ammar Khazal -4 years ago 74
Python Question

What is the difference between `print(x)` and `print(*x)` in python 3?

I can't remember where I saw this but I don't understand what's going on here. What use does

print(*x)
provide?
The following code:

x = [(1, 2), (3, 4)]
print(x)
print(*x)

y = [1, 2, 3, 4]
print(y)
print(*y)

z = 1, 2, 3, 4
print(z)
print(*z)


Gives the following output:

[(1, 2), (3, 4)]
(1, 2) (3, 4)
[1, 2, 3, 4]
1 2 3 4
(1, 2, 3, 4)
1 2 3 4


I see what is happening but I don't know what is happening. In the previous cases, it just outputs them without any brackets or commas.
But when I use this with a dictionary:

a = {1: "a", 2: [1, 2, 3], 3: (4, 5, 6)}
print(a)
print(*a)


I only get the keys back with the second print:

{1: 'a', 2: [1, 2, 3], 3: (4, 5, 6)}
1 2 3

Answer Source

It has been described here that * will "unpack the arguments out of a list or tuple". When you print(*var), it just like printing multiple variables:

x = [(1, 2), (3, 4)]
print(*x)
# (1, 2) (3, 4)
# Same as follow
for v in x:
    print(v, end=' ')

When you unpack a dict, it returns the key of the dict. That's why you only get the keys back by print(*dict). Applying the same for loop and you got the same as print(*a):

a = {1: "a", 2: [1, 2, 3], 3: (4, 5, 6)}
for v in a:
    print(v, end=' ')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download