0
0
Pythonprogramming~5 mins

Searching and counting elements in Python

Choose your learning style9 modes available
Introduction

We search and count elements to find if something is there and how many times it appears. This helps us understand and work with data easily.

Checking if a friend's name is in your contact list.
Counting how many times a word appears in a story.
Finding if a product is available in a shopping list.
Counting how many times a number appears in a list of scores.
Syntax
Python
element in collection
collection.count(element)

element in collection returns True if the element is found, otherwise False.

collection.count(element) returns how many times the element appears in the collection.

Examples
This checks if 'apple' is in the list fruits. It returns True.
Python
fruits = ['apple', 'banana', 'apple', 'cherry']
'apple' in fruits
This counts how many times 'apple' appears in the list fruits. It returns 2.
Python
fruits.count('apple')
This checks if the number 2 is in the list numbers. It returns True.
Python
numbers = [1, 2, 3, 2, 2, 4]
2 in numbers
This counts how many times 2 appears in the list numbers. It returns 3.
Python
numbers.count(2)
Sample Program

This program looks for the word 'pen' in the list items. It tells us if 'pen' is there and how many times it appears.

Python
items = ['pen', 'notebook', 'pen', 'eraser', 'pen']
search_item = 'pen'

# Check if the item is in the list
found = search_item in items

# Count how many times the item appears
count = items.count(search_item)

print(f"Is '{search_item}' in the list? {found}")
print(f"Number of times '{search_item}' appears: {count}")
OutputSuccess
Important Notes

Searching with in is simple and fast for small lists.

Counting with count() works on lists, tuples, and strings.

Both methods are case-sensitive for strings.

Summary

Use in to check if an element exists in a collection.

Use count() to find how many times an element appears.

These tools help you quickly find and count things in your data.