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 –
Method 1: Print Whole Tuple At Once
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 –
Method 2: 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,
- len() method returns length of tuple.
- range() method returns range of elements from 0 upto provided length
- 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.
- 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
Method 3: Print Elements of Tuple Without Array Indexing
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,
- In each iteration, name contains element of tuple at that iteration.
- 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.