So I am trying to do this:
tuple([1])
The output I expect is :
(1)
However, I got this:
(1,)
But if I do this:
tuple([1,2])
It works perfectly! like this:
(1,2)
This is so weird that I don't know why the tuple function cause this result.
Please help me to fix it.
This is such a common question that the Python Wiki has a page dedicated to it:
That is normal behavior in Python. You get a Tuple with one element. The notation (1,) is just a reminder that you got such a tuple.
What you are getting is a tuple. When there is only a single element, then it has to be represented with a comma, to show it is a tuple.
Eg)
The reason is, when you do not use a comma when there is only one element, the interpreter evaluates it like an expression grouped by paranthesis, thus assigning
a
with a value of the type returned by the expressionThat is how tuples are formed in python. Using just
(1)
evaluates to 1, just as much as using(((((((1)))))))
evaluates to((((((1))))))
to(((((1)))))
to... 1.Using
(1,)
explicitly tells python you want a tuple of one element(1)
is just1
in grouping parentheses - it's an integer.(1,)
is the 1-element tuple you want.The output (1,) is fine. The , is to mark a single element tuple.
If
a is really a integer
If
Then a is a tuple.