🐍 Python for kids · Class 7 · Lesson 12 of 18 · Free
Searching Data – Find Anything in Lists and Dictionaries
⏱ About 30 minutes · ▶ run real Python here — nothing to install · no sign-in
In this lesson you will
- Check for items with in, and find positions with index() and find().
- Write a linear search function and find every match in a list.
- Look up values safely with get(), and explain how binary search works.
You type a friend's name in your phone contacts, and the number appears at once. Behind that is a search. Today you will learn several ways to search data, and write your own.
How do I check if an item is in a list, string or dictionary?
The word in answers yes or no: True or False. It works on lists, strings, sets and dictionaries.
On a string, in checks for a piece of text anywhere inside it.
On a dictionary, in checks only the keys. To check the values, use .values().
▶colours = ["red", "green", "blue"]2print("green" in colours)3print("dia" in "India")4prices = {"tea": 10, "coffee": 20}5print("tea" in prices)6print(10 in prices)7print(10 in prices.values())
No variables yet.
▌✏️ Change this code and run it yourself
True True True False True
How do I find the position of an item in Python?
index() gives the position of the first match. count() tells how many times an item appears.
If the item is missing, index() stops the program with a ValueError. So check with in first.
Strings have find(), which is gentler. It returns -1 when the text is not found.
First 45 at index 1 45 appears 2 times 99 is not in the list 2 -1
How do I write my own linear search?
A linear search checks items one by one, from the start, until it finds the target.
Our function returns the index as soon as it finds a match. That return ends the loop early.
Only after checking every item does it return -1, meaning not found.
▶def linear_search(items, target):2 for i, item in enumerate(items):3 if item == target:4 return i5 return -167bag = ["pen", "ruler", "eraser"]8print(linear_search(bag, "ruler"))9print(linear_search(bag, "glue"))
No variables yet.
▌✏️ Change this code and run it yourself
1 -1
💡 This is roughly what index() does for you. Writing it yourself shows how the search really works.
How do I find all the matches, not just the first?
index() stops at the first match. To get every match, use a list comprehension.
With enumerate(), we can keep the positions of all matches. With records, we keep whole dictionaries.
An empty list [] as the answer simply means nothing matched.
▶results = ["W", "L", "W", "W", "L"]2wins = [i for i, r in enumerate(results) if r == "W"]3print("Won matches at index:", wins)4students = [{"name": "Riya", "marks": 88}, {"name": "Om", "marks": 64}, {"name": "Zoya", "marks": 91}]5high = [s["name"] for s in students if s["marks"] > 80]6print("Above 80:", high)
No variables yet.
▌✏️ Change this code and run it yourself
Won matches at index: [0, 2, 3] Above 80: ['Riya', 'Zoya']
How do I look up a value safely in a dictionary?
A dictionary finds a key almost instantly, even with thousands of keys. It does not check items one by one.
d[key] crashes with a KeyError if the key is missing. d.get(key, default) returns the default instead.
Below, a user types a city and we look up its PIN code.
City: Mumbai PIN code: 400001 PIN code: not in our list
What is binary search, and why is it so fast?
Think of guessing a number from 1 to 100. A smart player always guesses the middle and halves the range.
Binary search does the same on a sorted list. Each check throws away half of the items.
For 1,000 items, a linear search may need 1,000 checks. Binary search needs only about 10.
73 is at index 72, found in 6 steps 500 gives -1, after 7 steps
💡 Binary search only works on a sorted list. Sort first, as you learned in the last lesson.
🤔 Predict the output
Think like Python: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
d = {"tea": 10, "coffee": 20}
print(10 in d, "tea" in d)Question 2. What does this print?
x = [4, 7, 4, 9] print(x.index(4), x.count(4))
Question 3. What does this print?
s = "banana"
print(s.find("na"), s.find("x"))🧩 Your challenge
A list of trains stores each train's name and its stops. Ask the user for a station name. Print every train that stops there. If no train stops there, print "No train found".
Station: Pune Deccan Queen stops at Pune Indrayani stops at Pune
⚠️ Common mistakes (and how to fix them)
❌ Wrong
bag = ["pen", "ruler"]
print(bag.index("glue"))ValueError: 'glue' is not in list
✅ Right
bag = ["pen", "ruler"]
if "glue" in bag:
print(bag.index("glue"))
else:
print("glue is not in the bag")index() crashes when the item is missing. Check with in first, then ask for the position.
❌ Wrong
def search(items, target):
for i, item in enumerate(items):
if item == target:
return i
else:
return -1
print(search([5, 8, 3], 8))No error message – but it prints -1, even though 8 is in the list.
✅ Right
def search(items, target):
for i, item in enumerate(items):
if item == target:
return i
return -1
print(search([5, 8, 3], 8))The else returns after checking only the first item. Return -1 after the loop, once every item is checked.
❌ Wrong
capitals = {"Kerala": "Thiruvananthapuram", "Bihar": "Patna"}
print("Patna" in capitals)No error message – but it prints False, even though Patna is in the dictionary.
✅ Right
capitals = {"Kerala": "Thiruvananthapuram", "Bihar": "Patna"}
print("Patna" in capitals.values())in checks only the keys of a dictionary. Patna is a value, so search capitals.values() instead.
📌 Remember
- in gives True or False; on a dictionary it checks only the keys.
- index() gives the first position, but crashes if the item is missing.
- find() on strings returns -1 instead of crashing.
- A linear search checks items one by one and returns -1 only after the loop.
- A list comprehension finds all matches, and d.get(key, default) looks up safely.
- Binary search halves a sorted list at each step, so it is very fast.
Finished the quiz and the challenge?
Questions students ask
Which is faster: searching a list or a dictionary?
A dictionary. It jumps straight to the key, while a list may check every item one by one.
Why does my search return -1?
-1 is a common way to say not found, because positions counted from the start are never negative.
Why must the list be sorted for binary search?
Binary search decides to go left or right by comparing with the middle. That only works when items are in order.
How do I search without caring about capital letters?
Change both sides to small letters first, for example target.lower() in name.lower().