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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.