Q:

Python program to check if the element is present in tuple

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Checking if the element is present in tuple

In this article, we are given a tuple and an element. Our task is to create a python program to check if the given element is present in the tuple.

Input:
(4, 1, 7, 8, 2)
ele = 4

Output:
present

For this, we need to perform a searching algorithm on elements of the tuple. And find the presence of the given element. This can be easily done in Python using one of the multiple methods provided.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to check for the presence of the given element is by simply iterating over the tuple and comparing each element with the given element. Break if an element from tuple is matched, otherwise continue.

# Python program to check if the 
# element is present in tuple

# Initializing and printing the tuple 
# and search element
myTuple = (5, 2, 7, 9, 1, 4)
print("The element of the tuple are " + str(myTuple))
ele = 9
print("The search element is " + str(ele))

# Checking for the presence of the 
# element is tuple
isPresent = False
for val in myTuple :
	if ele == val :
		isPresent = True
		break

# Printing result
if isPresent : 
    print("The element is present in the tuple")
else :
    print("The element is not present in the tuple")

Output:

The element of the tuple are (5, 2, 7, 9, 1, 4)
The search element is 9
The element is present in the tuple

Method 2:

Another method to solve the problem is by using Python's built-in in operator. This operator checks for the presence of the given element in the tuple and returns a boolean value for the result.

# Python program to check if the element 
# is present in tuple

# Initializing and printing the tuple and search element
myTuple = (5, 2, 7, 9, 1, 4)
print("The element of the tuple are " + str(myTuple))
ele = 9
print("The search element is " + str(ele))

# Checking for the presence of the element is tuple
isPresent = ele in myTuple

# Printing result
if isPresent : 
    print("The element is present in the tuple")
else :
    print("The element is not present in the tuple")

Output:

The element of the tuple are (5, 2, 7, 9, 1, 4)
The search element is 9
The element is present in the tuple

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check if a tuple is a subset of ... >>
<< Python program to convert tuple to integer...