It's not simple to create a tuple with one element, if we try to create a tuple with parenthesis or without parenthesis, tuple will not be created.
创建具有一个元素的元组并不简单,如果我们尝试创建带有括号或不带括号的元组,则不会创建元组。
Consider the below example,
考虑下面的示例,
tuple1 = ("Hello")
print("type of tuple1: ", type(tuple1))
tuple2 = "Hello"
print("type of tuple2: ", type(tuple2))
Output
输出量
type of tuple1: <class 'str'>
type of tuple2: <class 'str'>
See the output, the type of tuple1 and tuple2 is str.
看到输出, tuple1和tuple2的类型为str 。
Then, how to create a tuple with one element?
然后, 如何用一个元素创建一个元组?
It's little tricky to create a tuple with one element, we need to use a trailing comma after the element that represents that it is a tuple.
创建具有一个元素的元组有点麻烦, 我们需要在表示它是元组的元素后使用尾随逗号 。
Consider the below example,
考虑下面的示例,
tuple1 = ("Hello",)
print("type of tuple1: ", type(tuple1))
tuple2 = "Hello",
print("type of tuple2: ", type(tuple2))
tuple3 = (100,)
print("type of tuple3: ", type(tuple3))
tuple4 = 100,
print("type of tuple4: ", type(tuple4))
Output
输出量
type of tuple1: <class 'tuple'>
type of tuple2: <class 'tuple'>
type of tuple3: <class 'tuple'>
type of tuple4: <class 'tuple'>
Now, see the output, the type of variables is tuple. Hence, we can create one element tuple by using a trailing comma after the element and it works with and without parenthesis.
现在,查看输出,变量的类型为tuple 。 因此,我们可以通过在元素后使用尾部逗号来创建一个元素元组,并且该元素可以在带或不带括号的情况下使用。
翻译自: https://www.includehelp.com/python/creating-a-tuple-with-one-element.aspx