Contains in Python
In Python, “contains” refers to the presence of a given item in some collection, whether it is a string, list, set, tuple, or dictionary. Such functionality is obtained through the use of the in keyword or certain methods available with these data structures. Here is the detailed description:
1. Using the in keyword
The in keyword is used to check for membership in a collection. It returns True if the item exists and False otherwise.
Examples:
- Strings:
- Strings are sequences of characters. You can check if a substring exists within a string.
text = "Python is amazing"
print("Python" in text) # True
print("Java" in text) # False
2. Lists:
- Lists are sequential groups, and you verify whether an item exists within the list.
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # True
print(6 in numbers) # False
3. Tuples:
- Tuples are similar to lists but are immutable. The
inkeyword works the same way.
fruits = ("apple", "banana", "cherry")
print("banana" in fruits) # True
print("orange" in fruits) # False
4. Sets:
- Sets are unordered collections of unique elements. Membership checks are very efficient in sets.
unique_numbers = {1, 2, 3, 4, 5}
print(3 in unique_numbers) # True
print(6 in unique_numbers) # False
5. Dictionaries:
- In dictionaries, the
inkeyword checks for the existence of keys, not values.
student_grades = {"Alice": 85, "Bob": 90, "Charlie": 78}
print("Alice" in student_grades) # True
print(85 in student_grades) # False
2. Using specific methods
Python collections also provide methods to determine if an item exists.
Examples:
- Strings:
- The
.find()method returns the index of the first occurrence of a substring or-1if it’s not found.
text = "Python is amazing"
print(text.find("amazing")) # 10
print(text.find("Java")) # -1
- The
.count()method counts occurrences of a substring.
text = "Python is amazing"
print(text.count("is")) # 1
2. Lists and Tuples:
- The
.count()method counts occurrences of an element.
numbers = [1, 2, 3, 4, 3, 3]
print(numbers.count(3)) # 3
- You can combine
inwith.index()to find the index of an element (only if it exists).
numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
print(numbers.index(3)) # 2
3. Dictionaries:
- To check if a value exists, use
.values().
student_grades = {"Alice": 85, "Bob": 90, "Charlie": 78}
print(85 in student_grades.values()) # True
- To check if a key-value pair exists, use
.items().
print(("Alice", 85) in student_grades.items()) # True
3. Custom Classes and the __contains__ Method
In user-defined classes, you can define how in behaves by implementing the __contains__ method.
Example:
class MyCollection:
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items
collection = MyCollection([1, 2, 3])
print(2 in collection) # True
print(5 in collection) # False
Output:
True
False
4. Behind the Scenes
The in keyword internally calls special methods like:
- For strings, lists, tuples, sets:
__contains__() - For dictionaries:
(for keys)__contains__()
When in is used, Python optimizes the membership check depending on the data structure:
- Lists/Tuples: Linear search (O(n) time complexity).
- Sets/Dictionaries: Hash table lookup (O(1) average time complexity).
Summary Table:
| Data Structure | What in Checks | Efficiency |
|---|---|---|
| String | Substring | O(n) |
| List | Element | O(n) |
| Tuple | Element | O(n) |
| Set | Element | O(1) (average) |
| Dictionary | Key | O(1) (average) |