Search code examples
pythonpython-3.xtuplespython-3.5

How to perfectly convert one-element list to tuple in Python?


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.


Solution

  • This is such a common question that the Python Wiki has a page dedicated to it:

    One Element Tuples

    One-element tuples look like:

    1,

    The essential element here is the trailing comma. As for any expression, parentheses are optional, so you may also write one-element tuples like

    (1,)

    but it is the comma, not the parentheses, that define the tuple.