Test if Tuple contains K in Python

If it is required to check if a tuple contains a specific value 'K', it can be done using various methods including the in operator, the any method with map, and lambda functions.

The in operator is the most straightforward way to check membership in Python collections. For more complex conditions, we can use the any method which checks if any element in an iterable is True.

Anonymous function is a function which is defined without a name. In general, functions in Python are defined using def keyword, but anonymous function is defined with the help of lambda keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.

The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns an iterator as the result.

Using the 'in' Operator

The simplest method to check if a tuple contains a value is using the in operator ?

my_tuple = (67, 45, 34, 56, 99, 123, 10, 56)

print("The tuple is:")
print(my_tuple)
K = 67
print("The value of 'K' has been initialized")

my_result = K in my_tuple

print("Does tuple contain the K value?")
print(my_result)
The tuple is:
(67, 45, 34, 56, 99, 123, 10, 56)
The value of 'K' has been initialized
Does tuple contain the K value?
True

Using any() with map() and lambda

For more complex conditions, you can use any with map and lambda functions ?

my_tuple = (67, 45, 34, 56, 99, 123, 10, 56)

print("The tuple is:")
print(my_tuple)
K = 67
print("The value of 'K' has been initialized")

my_result = any(map(lambda elem: elem == K, my_tuple))

print("Does tuple contain the K value?")
print(my_result)
The tuple is:
(67, 45, 34, 56, 99, 123, 10, 56)
The value of 'K' has been initialized
Does tuple contain the K value?
True

Using any() with Generator Expression

A more Pythonic approach is using any with a generator expression ?

my_tuple = (67, 45, 34, 56, 99, 123, 10, 56)

print("The tuple is:")
print(my_tuple)
K = 67
print("The value of 'K' has been initialized")

my_result = any(elem == K for elem in my_tuple)

print("Does tuple contain the K value?")
print(my_result)
The tuple is:
(67, 45, 34, 56, 99, 123, 10, 56)
The value of 'K' has been initialized
Does tuple contain the K value?
True

Comparison

Method Performance Readability Best For
in operator Fastest Excellent Simple membership testing
any() + map() + lambda Slower Good Complex conditions
any() + generator Fast Excellent Complex conditions

Conclusion

Use the in operator for simple membership testing as it's the most efficient and readable. For complex conditions, prefer any() with generator expressions over map() and lambda for better performance and readability.

Updated on: 2026-03-25T17:07:56+05:30

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements