script_16.py - List Searching
Code
See script_16.py for full code.
Explanation
Line 20: prices = [p["price"] for p in products]
- List comprehension extracting one field
- p is dict, p["price"] is value
- Creates list of integers from list of dicts
Line 22: print(f"Is $300 in prices? {300 in prices}")
- in operator for membership testing
- Linear search O(n)
- Returns boolean
Line 29: def find_by_id(products, target_id):
- Function to find first match
Line 31: for product in products:
- Iterates until match found
Line 32: if product["id"] == target_id:
- Compares dict value
Line 33: return product
- Exits function immediately
- Returns the matching dict
Line 34: return None
- If loop completes without return
- Indicates "not found"
Line 40: def find_product(products, **criteria):
- **criteria captures keyword arguments as dict
- Allows flexible search: find_product(name="Laptop") or find_product(category="furniture", price=300)
Line 41: return next(...)
- next() gets first element from iterator
- Second argument is default if iterator empty
Line 42: (p for p in products if all(p.get(k) == v for k, v in criteria.items()))
- Generator expression (parentheses, not brackets)
- all() returns True if all conditions True
- p.get(k) safely accesses dict (returns None if key missing)
- criteria.items() is dict of search criteria
- Checks all criteria must match
Line 49: electronics = [p for p in products if p["category"] == "electronics"]
- List comprehension for filtering
- Returns all matches (not just first)
Line 59: idx = numbers.index(30)
- .index() finds first occurrence
- Returns integer position
- Raises ValueError if not found
Line 65: all_indices = [i for i, x in enumerate(numbers) if x == 30]
- enumerate provides indices
- Comprehension filters matching positions
- Returns list of all indices
Line 71: import bisect
- bisect module for binary search
Line 73: sorted_prices = sorted(prices)
- Binary search requires sorted data
- sorted() creates new sorted list
Line 77: idx = bisect.bisect_left(sorted_prices, target)
- .bisect_left() finds insertion point
- O(log n) complexity (fast)
- Returns index where target should be inserted
- Maintains sorted order
Line 78: if idx < len(sorted_prices) and sorted_prices[idx] == target:
- Verifies element actually exists at that position
- bisect only finds position, must check value
Line 84: has_expensive = any(p["price"] > 1000 for p in products)
- any() returns True if any element satisfies condition
- Generator expression (not list)
- Short-circuits (stops at first True)
Line 87: all_positive_prices = all(p["price"] > 0 for p in products)
- all() returns True if all elements satisfy condition
- Short-circuits (stops at first False)