1

I saw some weird printout when I had a variable followed by a comma and I was wondering what the Python interpreter really does when it encounters it.

def new_func():
    x = 1
    y = 2
    return x,y

x = 0
x,
y = new_func()

print(x,y)

Output: 0 (1,2)

So what exactly was printed? How did Python handle x,↵? What can I use this for?

wjandrea
  • 23,210
  • 7
  • 49
  • 68
PhantomQuest
  • 309
  • 2
  • 10

1 Answers1

4

In general, in Python the comma makes something a tuple. The newline does not have any effect.

E.g. i = 1, is equivalent to i = (1,)

General Example:

>>> 1
1
>>> 1,
(1,)

Your case:

>>> x = 0

>>> type(x)
int

>>> x,
(0,) # this is just the printed version of x as tuple

>>> x = x, # actual assignment to tuple

>>> type(x)
tuple
seralouk
  • 27,314
  • 8
  • 98
  • 117
  • 2
    So in other words, it wrapped x in a tuple, then discarded it; basically having no effect. – Carcigenicate Jul 23 '19 at 19:38
  • no you did not wrap. you just printed the tuple version of it. to wrap you need `i = 1`, `i = i,` . Then i becomes a tuple. see my answer – seralouk Jul 23 '19 at 19:43
  • I'm not the OP. They seem to be asking what `x,` on its own line does. "How did Python handle `x,↵`". – Carcigenicate Jul 23 '19 at 19:44
  • yes. the OP just printed the tuple version of it by typing `x,` – seralouk Jul 23 '19 at 19:45
  • So it seems that the line `y = new_func()` assigns a tuple since it did not find a second variable to unpack to. so `y` is now a tuple of `new_func()`'s `x,y` return. The `x,` was just an unassigned tuple. So the statement `print(x,y)` ends up printing x-->`0` (which was globally assigned) and then y-->`(1,2)`. – PhantomQuest Jul 24 '19 at 00:14