You can create tuple in python by writing elements between parentheses i.e. (). All tuple elements should be separated by a comma “,”.
You can store different types of items in the tuples. The following are a couple of examples to create Tuples in Python.
# Create an empty tuple.
a_tpl = ()
# Assign integer items to a tuple.
b_tpl = (1, 2, 3, 4)
# Assign character items to a tuple.
c_tpl = ('a', 'b')
# Assign homogenous items to a tuple.
d_tpl = ('a', 'topictrick.com', 1)
# Nested Tuple in Python.
n_tpl = (1, 2, ('a','b'))
You can create a tuple without parentheses by writing element delimited by a comma “,”. Let’s look at a couple of examples below.
# Create Python Tuple without parentheses.
e_tpl = 1, 2, 3, 4
Important Point: The point to remember is that if do not use brackets, it will become a tuple and not a list or any other datatype.
What is Python Tuple() Function?
Python tuple function is a built-in function. Tuple function converts the passed value into a tuple. The following example converts the list into a tuple.
# Create tuple by using Python Tuple Method.
a_lst = [1, 2, 3, 4 ,5]
g_tpl = tuple(a_lst)
print("Tuple Value :", g_tpl)
Tuple Value : (1, 2, 3, 4)
Another way to create a tuple is by using range() function. Let’s create a tuple that contains the number from 0 to 9.
# Create tuple by using Python range() function.
g_tpl = tuple(range(10))
print("Tuple :", g_tpl)
Tuple : (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)