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 print(*x)
does it 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 can see what's going on, but I don't know what's going on. In the previous cases, it just outputs them without any parentheses 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 keys with the second print:
{1: 'a', 2: [1, 2, 3], 3: (4, 5, 6)}
1 2 3
source to share
It has been described here that it *
will "unpack arguments from a list or tuple". When you do print(*var)
, this just prints out a few 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 it dict
, it returns a key dict
. This is why you only return keys print(*dict)
. Applying the same loop for
and you ended up with the same as print(*a)
:
a = {1: "a", 2: [1, 2, 3], 3: (4, 5, 6)}
for v in a:
print(v, end=' ')
source to share