Lesson 12
Searching Data
Find items efficiently in collections
1Searching for Items in Collections✨
In Python, we often work with collections of data like lists and dictionaries. Searching through these collections efficiently is an important skill. Let's explore some methods to find items quickly!
2Using the `in` Operator🎯
The `in` operator lets you check if an item exists in a collection. It's simple and effective for lists and sets.
3Example:💡
my_list = [10, 20, 30, 40, 50]
print(30 in my_list) # Output: TrueThis checks if 30 is in `my_list`.
Finding Index with `index()`
If you need to know the position of an item in a list, you can use the `index()` method. This will return the index of the first occurrence of the item.4Example:🚀
my_list = [10, 20, 30, 40, 30]
print(my_list.index(30)) # Output: 2This tells us that 30 is located at index 2.
5Searching in Dictionaries🔍
Dictionaries allow for fast lookups. You can check if a key exists using `in` and get its value directly.
6Example:⭐
my_dict = {'a': 1, 'b': 2, 'c': 3}
print('b' in my_dict) # Output: True
print(my_dict['b']) # Output: 2This shows how to check for a key and retrieve its value.
7Using List Comprehensions for Filtering🧩
List comprehensions can help you create a new list based on existing data. This is useful for searching and filtering items.
8Example:🎈
numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4]Here, we created a list of even numbers from the original list.
9Practice Makes Perfect✨
Now it's your turn! Try creating a program that searches for a specific item in a list and returns its index. Remember to handle cases where the item might not be present! Happy coding!
🎯 Practice Challenges
Master Searching Data by completing all 3 difficulty levels
Searching Data - Easy Challenge
Start with the basics. Perfect for beginners!
Searching Data - Medium Challenge
Get more challenging. Build your confidence!
Searching Data - Hard Challenge
Master this concept. Prove your skills!
🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →
Ready to Master Searching Data? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 11: Sorting DataOrder lists and dictionaries by key
- Next lesson →Lesson 13: RecursionFunctions that call themselves
- Grade 8 courseJavaScript Basics - Web ProgrammingJavaScript coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 7 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.