In this post we will write a python program that finds an element’s index or position in a tuple.
Before writing the program let’s understand what is a Tuple.
A Tuple in Python is depicted through round brackets/parenthesis and can be created by comma separated elements inside parenthesis. Tuples are immutable. It means you can’t change elements of a Tuple.
Example of Tuple:
() – Empty Tuple
(3,4,5) – Tuple of Integers
(‘q’,’w’,’e’,’r’,’t’,’y’) – Tuple of Characters
The below simple code creates and prints the Tuple.
myTuple = ('Q','W','E','R','T','Y')
print(myTuple)
Now Let’s write the program to find an element’s index or position.
myTuple = ('p','y','t','h','o','n')
char = input("Enter a single character from the string : ")
if char in myTuple:
count = 0
for elem in myTuple:
if elem != char:
count += 1
else:
break
print(char,"is at index",count,"in",myTuple)
else:
print(char,"is not in",myTuple)
Output:
I hope you will like this post. Happy Blogging!