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

      

+3


source to share


3 answers


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=' ')

      

+1


source


In python datatypes like list, dictionary .. * will unpack values ​​from it ...

For a better understanding,
  a = ["someone", 23] "hi my name {} my age {}". Format (a [0], a [1])



You can achieve the same, "hello my name is {} my age is {}". Format (* a)

+1


source


* x is shorthand for unpacking values.

therefore for a list x (1, 2, 3, 4) 
*x is 1, 2, 3, 4 as unpacked values

      

Read this for more information on unpacking

0


source







All Articles