Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 579
Mars Lee Avatar asked Apr 15 '16 03:04

Mars Lee


People also ask

How do you convert an element to a list to a tuple?

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.

How do you make a tuple with one element in Python?

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.

How do you convert each item to a tuple in Python?

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.

How do you convert a list to a list of tuples?

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.


2 Answers

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.

like image 117
Akshat Mahajan Avatar answered Oct 07 '22 05:10

Akshat Mahajan


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

like image 24
smac89 Avatar answered Oct 07 '22 06:10

smac89