Write a Program to Demonstrate Working With Tuples in Python

Python Tuple is a immutable sequence that contain multiple data types separated using comma and enclosed with round braces.

 

python tuple demo

 

 

In the below program lets perform four operations of tuple.

1) Create empty tuple, ask user to add items in the tuple.

2) Read all the items of tuple.

3) Check if element is present or not in tuple 

4) Then count the number of occurrences of each tuple element and print it.


First : Create empty tuple, ask user to add items in the tuple

n = int(input("Enter Length of Tuple : "))
basket = ()
for index in range(n):
    temp = input(f"Enter Item #{index + 1} : ")
    basket += (temp,)

 

Second : Read and Print all the items of tuple using for loop

print("Items in tuple are ...")
for item in basket:
    print(item)


Third : Check if element is present or not in tuple 

temp = input("Enter Item to Check : ")
try:
    my_index = basket.index(temp)
    print("Item present at index :", my_index)
except ValueError:
    print("Item is not present in tuple")

 

Fourth : Then count the number of occurrences of each tuple element and print it

for item in set(basket):
    print(f"{item} occurs : {basket.count(item)} times")


Complete Program : 

n = int(input("Enter Length of Tuple : "))
basket = ()
for index in range(n):
    temp = input(f"Enter Item #{index + 1} : ")
    basket += (temp,)

print("\nItems in tuple are ...")
for item in basket:
    print(item)

temp = input("\nEnter Item to Check : ")
try:
    my_index = basket.index(temp)
    print("Item present at index :", my_index)
except ValueError:
    print("Item is not present in tuple")

print("\nCount of each item in tuple ... ")
for item in set(basket):
    print(f"{item} occurs : {basket.count(item)} times")


OUTPUT : 

# python main.py

Enter Length of Tuple : 5
Enter Item #1 : apple
Enter Item #2 : apple
Enter Item #3 : banana
Enter Item #4 : orange
Enter Item #5 : orange


Items in tuple are ...
apple
apple
banana
orange
orange
 

Enter Item to Check : strawberry
Item is not present in tuple
 

Count of each item in tuple ...
orange occurs : 2 times
banana occurs : 1 times
apple occurs : 2 times 


Conclusion : Try to run all the program by yourself and comment down below if you have any issue.

 

 

Post a Comment

0 Comments