Python Program to Print Tuple (With Example)

In this article, we will learn how to write python program to print tuple or elements of tuple.

At first, we will learn how to write program to print tuple itself in python. It can be done in many ways –

  1. Print Whole Tuple At Once
  2. Print Elements of Tuple One by One
  3. Print Element Without Array Indexing

Consider we have below tuple with string elements –

samplTuple = ('Android', 'Tutorialwing', 'Python', 'Kotlin')

Now, if we want to print above tuple, we can do so using name of the tuple.

samplTuple = ('Android', 'Tutorialwing', 'Python', 'Kotlin')

print("Tuple: ")
print(samplTuple) 

Notice that we have only used name of the tuple to print whole at once.

When we run above program, output is –

Tuple: 
('Android', 'Tutorialwing', 'Python', 'Kotlin')

Now, let’s assume we have another tuple with integer elements only. We can also print this tuple using name of the tuple as shown below –

sampleTuple = (14, 230, 360, 410, 500)

print("Tuple: ")
print(sampleTuple)

We have printed using name of the tuple.

When we run above program, output is –

Tuple: 
(14, 230, 360, 410, 500)

Similarly, we can use name of the tuple to print whole tuple at once. Now, what if we want to print only elements present in the tuple ?

So, we will learn to print elements of tuple –

Consider we have a tuple as shown below –

sampleTuple1 = (180, 250, 330, 460, 510)

Elements of above tuple can be printed using for loop as shown below –

sampleTuple = (180, 250, 330, 460, 510)

print("Tuple: ")
for i in range(len(sampleTuple)):
    print("Index: %d, Item = %d" %(i, sampleTuple[i]))

Here,

  1. len() method returns length of tuple.
  2. range() method returns range of elements from 0 upto provided length
  3. for loop run a loop from 0 to given range. Then, each element of tuple is accessed using index as tuple[i], where is index of element and tuple is our sample tuple.
  4. Finally, element is printed using print() method.

When we run above program, output is –

Tuple: 
Index: 0, Item = 180
Index: 1, Item = 250
Index: 2, Item = 330
Index: 3, Item = 460
Index: 4, Item = 510

Elements of tuple can also be accessed without array indexing. We can run a for loop that can have elements in each iteration as shown below –

nameTuple1 = ('Mike', 'Rohan', 'Tutorialwing', 'Android')
print("Tuple: ")
for name in nameTuple1:
    print(name)

Here,

  1. In each iteration, name contains element of tuple at that iteration.
  2. Finally, name is printed using print() method in python.

When we run above program, output is –

Tuple: 
Mike
Rohan
Tutorialwing
Android

That’s how we can write python program to print tuple or elements of tuple.

Leave a Reply