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.
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
To create a tuple with only one item, you have add a comma after the item, otherwise Python will not recognize the variable as a tuple.
Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.
To convert a list of lists to a list of tuples: Pass the tuple() class and the list of lists to the map() function. The map() function will pass each nested list to the tuple() class. The new list will only contain tuple objects.
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.
That 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With