Home » Python

Creating a tuple with one element in Python

In this tutorial, we are going to learn how to create a tuple with one element in Python programming language?
Submitted by IncludeHelp, on November 14, 2019

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.

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.