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
Ammar Khazal
  • 133
  • 3
  • 9
  • regarding dictionaries, iterating over a dictionary iterates over the *keys*. When you unpack an argument using `*`, it simply iterates over your container. – juanpa.arrivillaga Jun 11 '17 at 19:26

3 Answers3

1

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=' ')
Y. Luo
  • 5,622
  • 1
  • 18
  • 25
1

In python data types like list, dictionary.. * will unpack values from it...

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

You can achieve the same by , "hi my name {} my age is {} ".format(*a)

Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
0

*x is a shorthand for value unpacking.

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

SerialDev
  • 2,777
  • 20
  • 34