For and while loop to display each element of a tuple

This blog contain program which display elements from a tuple using for and while loop

Create a tuple of number containing 8 numbers

tup = (1,2,3,4,5,6,7,8)

Find number of elements inside tuple using len() function and print the number of elements

l = len(tup)
print('Number of Elements:',l)

Create a variable and initialize with 0 value

i = 0

Use while loop to display each element from a tuple


while i<l:
    print(tup[i])
    i+=1

Use for loop to display elements from a tuple

for t in tup:
    print(t)

Output

Number of Elements: 8
While loop to display tuple elements
1
2
3
4
5
6
7
8
For loop to display tuple elements
1
2
3
4
5
6
7
8

Complete Code

tup = (1,2,3,4,5,6,7,8)
l = len(tup)
print('Number of Elements:',l)
i = 0
print('While loop to display tuple elements')
while i<l:
    print(tup[i])
    i+=1
print('For loop to display tuple elements')
for t in tup:
    print(t)
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s