Reputation: 12418
I noticed by accident that Python's primitive math operators support commas in both numeric arguments. A tuple is returned. What is it doing and why is this syntax supported?
Here are a few examples:
>>> 2,10,2 / 2
(2, 10, 1)
>>> 2,10,2 * 2
(2, 10, 4)
>>> 2,10,2 % 2,3
(2, 10, 0, 3)
Upvotes: 2
Views: 1214
Reputation: 302
You are just defining a tuple, it's not that math operators supports commas. What python is doing there, is assuming you are doing a tuple (because of the commas), so it evaluate each value between the comas, and then store it to the tuple. Not a thing about primitive math operator, it's just how python interprets commas.
You could do 1,"a","a"+"b",2+5
, and that would give you the tuple (1, "a", "ab", 7)
.
An easy and simplist way of giving an answer is: If python finds a comma in your code, it assumes you put it there for separating data. Then, if he finds 1, 1+1
, you are giving two data, a number one, and an expresion 1+1. Python evaluates the expresion and says "Oh, its 2". Then, he returns you the (1,2)
tuple.
Im not an expert at python compiler, so don't rely 100% on my answer, but I'm quite sure that's the reason.
Upvotes: 0
Reputation: 146
You are actually using a tuple (which is why the output is surrounded by the parenthesis.) The math is only happening on one element of the tuple.
https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
Upvotes: 1
Reputation: 77837
This is especially visible in interactive mode. Python semantics turn a comma-separated sequence into a tuple. This underlies the "tuple unpacking" you know from function returns, such as
value, status = my_func(args)
If you write
a, b, c = 1, 2, 3
You get the corresponding assignments just as if you'd put (1, 2, 3)
on the RHS. Similarly,
a = 1, 2, 3
Gets you an a
value of the entire tuple, (1, 2, 3)
.
Note that you need an all-or-none approach: one variable on the LHS, or exactly the correct quantity for the tuple length.
Upvotes: 0
Reputation: 42007
In 2,10,2 / 2
, the operation performed actually is:
2, 10, (2 / 2)
Hence you get the (2, 10, 1)
as output.
In Python, tuples are actually a collection of values separated by commas, the surrounding parentheses are to avoid ambiguity.
Upvotes: 11