Search and Hashing
Almost every program looks things up: is this customer already in the list, which product has this id, which records have no match in the other file? On a hundred records any way of answering is instant. On a million, the way you answer decides whether the program finishes in a second or is still running after lunch, and the two programs look almost identical — both say if x in collection. So the question is what a lookup costs and how that cost grows with the data, and the steady way to measure it is to count comparisons rather than time them. Linear search looks at each item in turn, needs nothing from the data, and costs about n/2 comparisons for a key that is there and all n for one that is not. Once is harmless; inside a loop over another large collection it is quadratic, the usual reason a program that worked on a sample never finishes on the full file.
Two ways of organising the data change that cost. Binary search halves a sorted list each round, so a million items take twenty steps; it needs sorted data, fails silently without it, and the sorting has a price that only repeated lookups repay. Hashing does not search at all: a hash function computes which bucket a key must be in, and a lookup takes about one step whatever the size. Python’s dict and set are hash tables, which explains two rules met earlier without their reasons — a key must be immutable, and a dictionary has no order. That last point decides which structure to use: a hash table answers “is exactly this key here?”, while sorted data also answers “between”, “next”, and “starts with”. Before optimising anything else, look for a scan inside a loop; changing one list to a set is often the whole fix.

Listen
| Speaker | Text |
|---|---|
| Alex | So, um, imagine you’re looking at two identical unmarked doors, like same paint, same doorknob, same everything, |
| Sam | right, completely indistinguishable from the outside, |
| Alex | exactly. And on the surface, the physical action to open either door is exactly the same, you know, you just reach out and turn the knob, but behind door A is this, uh, perfectly organized filing cabinet where you can instantly grab the exact single document you need. |
| Sam | And behind door B, I’m guessing is not a filing cabinet, |
| Alex | definitely not. Behind door B is a massive, just chaotic pile of a million unsorted papers dumped all over the floor. |
| Sam | Yeah, so the physical action you take to open the door is deceivingly simple, but the reality of what happens the moment you cross that threshold is fundamentally different. I mean, one scenario is a near instant retrieval, and the other is just a time-consuming nightmare of sifting and sorting. |
| Alex | And you know that dynamic is playing out constantly in your code when you write the Python statement, like if X in collection. The syntax looks identical on your screen regardless of what that collection actually is. |
| Sam | It does. It’s clean. It’s highly readable, yeah, |
| Alex | but the invisible mechanics operating underneath that simple line of code, they are drastically different. And for you, uh, the graduate students in data science and analytics joining us for this deep dive as part of your Python programming class, understanding that invisible machinery is absolutely critical. |
| Sam | It genuinely is the dividing line between a robust data pipeline and one that just collapses under its own weight because almost every analytical script you write is going to look things up, right? Right. |
| Alex | Like, is this customer ID in the database or which product corresponds to this SKU |
| Sam | exactly. And when you’re dealing with 100 records, any method you use is going to appear instant. You really won’t notice a delay at all, |
| Alex | but you aren’t here to work with 100 records. You’re here to process. a million or, you know, 50 million at that scale, how your data is structured dictates whether your script finishes before you get back from grabbing a coffee or if it just outright crashes your server. Oh for sure. So our mission today is to uncover the why behind that performance gap. We’re going to look directly at the internal mechanics of linear search, binary search, and hashing. |
| Sam | And to do that effectively, we kind of need to build the skill of reasoning about computational cost before you ever hit run on your program. That requires a pretty big mindset shift in how we actually measure code performance. |
| Alex | OK, let’s unpack this because this is where I think a lot of us get tripped up. As data science students, our first instinct is to use the time module, |
| Sam | right? Oh, absolutely right. That’s everyone’s go |
| Alex | to, right? We write our script, check the start time, check the end time, and see how many seconds it took. It feels completely objective, but wait. My stakeholders only care if the monthly report finishes generating by 5 p.m. They don’t care about like abstract concepts like algorithmic steps. So why are the sources telling us to stop timing our code and count steps instead? Well, |
| Sam | that’s a highly practical question. The issue is that execution time is just a terrible liar when you’re trying to evaluate algorithmic efficiency. Really? How so? If you run the exact same script on the exact same data set 5 times, you will get 5 slightly different execution times. And if you’re running this on a shared cloud instance or even just your local laptop, those times can vary wildly. |
| Alex | I assume that’s because of system loads, like what else the computer’s trying to do at that exact millisecond. |
| Sam | Precisely. Your operating system might prioritize a background update right as your script runs, or, you know, your browser has 50 tabs open and it’s eating up all your available RAM. |
| Alex | Yeah, that happens to be all the time, right? |
| Sam | So the physical execution time depends heavily on your specific hardware and the current system load. It tells you nothing fundamental about the algorithm itself, but counting steps, |
| Alex | what do you mean by steps exactly? |
| Sam | Specifically, the number of comparisons a program makes between an item and your target. That is a constant mathematical metric. |
| Alex | Oh, OK. So 5 comparisons is 5 comparisons whether I’m running this on a 10-year-old laptop or a massive AWS cluster. |
| Sam | Yes, what’s fascinating here is that step counting answers the real question you will inevitably face in production, which is what happens when my data set grows 10 times larger, |
| Alex | because timing a tiny sample set can’t predict that growth curve accurately. |
| Sam | Exactly. But step counting gives you the exact mathematical trajectory of your computational cost, |
| Alex | which Uh, brings us to the default brute force method of searching, the linear search. This is the pile of papers on the floor behind door B. You just look at every single item one by one, sequentially until you find what you’re looking for. |
| Sam | Yeah, and Python’s default behavior for a list when you use the in keyword or methods like .index or .count is to execute a linear search. It requires absolutely nothing from the data itself, |
| Alex | so it doesn’t need to be sorted or anything. |
| Sam | Nope. It can be entirely random, and the search will still function perfectly fine. |
| Alex | I understand the mechanism there, but how bad does the math actually get for really large data sets? |
| Sam | Let’s look at the baseline. If you have, say, 1 items in a list and the target you want is actually in there, on average, you’ll have to inspect half the list before you stumble across it. So that’s n divided by two steps. |
| Alex | OK, but the average case isn’t what takes down a server. It’s the worst case scenario. What happens when the item you were looking for just isn’t in the list at all? |
| Sam | That is where performance falls off a cliff. To definitively prove that an item does not exist in an unsorted list, the algorithm has to check every single item. |
| Alex | OK, so you have to look at all 1 million papers on the floor to confidently say the document is missing. |
| Sam | Yes, that takes a full end steps every single time. |
| Alex | And in data science, asking, you know, is this a new customer or which of these records are missing from the master database are incredibly common queries. You are actively querying for things that are not there, |
| Sam | which means you are triggering that worst case scenario constantly. 10 times the data means 10 times the computational work. That is a linear cost which scales up reliably, but it scales up painfully. |
| Alex | That linear cost creates what I kind of think of as the silent killer of data pipelines. A linear search nested inside a loop. |
| Sam | Oh yeah, that’s a classic trap, |
| Alex | right? Imagine you are building a pipeline that processes a million recent orders. Inside your loop for every single order, you have a simple in statement, checking if the customer who made that order is present in a separate list of 100,000 VIP customers. |
| Sam | And it looks entirely innocent on the screen. You just write for order in orders, and then if order customer in VIP list. It’s highly readable, standard Python. |
| Alex | But the invisible math there is just staggering. For every single one of those million orders, Python’s scanning through the 100,000 VIP customers. |
| Sam | Right, which means your script is executing up to 100 billion comparisons. This is quadratic growth. |
| Alex | And it’s why you write a script, test it on a sample of 1000 rows, and it finishes in half a second. But then you deploy it to production with the full data set, and the pipeline just hangs indefinitely. |
| Sam | So if scanning sequentially is what’s freezing our pipelines, the obvious question is, uh, how do we structure the data so we can skip the scanning entirely. |
| Alex | We need a mechanism to rule out vast chunks of data at once rather than looking at things one by one. Exactly. It’s the classic binary search logic like the childhood game where you have to guess a number between 1 and 100. You would never start guessing sequentially, right? Like 1, then 2, then 3. No, |
| Sam | you’d instantly guess 50, right? |
| Alex | And if the answer is higher. You have immediately eliminated half the problem space. Python does exactly that. |
| Sam | It does, and it’s a profound optimization. But there is one absolute non-negotiable rule here. Binary search requires sordid data. Oh, |
| Alex | because the higher or lower feedback loop only works if the underlying data has a strict reliable order. |
| Sam | Exactly. Walk us through how Python actually executes that internally, if you don’t mind. Sure, |
| Alex | so it operates using two pointers, which you can think of as fences. You have a low fence and a high fence, |
| Sam | right? |
| Alex | Initially, the low fence is at the very beginning of your data set and the high fences at the end. The algorithm looks at the item exactly in the middle. If your target is alphabetically or numerically greater than that middle item, Python moves the low fence entirely past the middle. |
| Sam | So it completely ignores that lower half of the data. |
| Alex | Yeah, the loop maintains one mathematical guarantee. If the target exists, it is always fenced in between low and high. |
| Sam | I get that having the data is fast, but Practically how much faster is it for a million items? Are we saving a few seconds or are we saving hours? |
| Alex | You are saving lifetimes of compute. This is logarithmic growth. If you have a million items, how many times do you have to divide that massive list in half before you are left with just one single option? |
| Sam | Uh, I think it’s 20 times, |
| Alex | yep, only 20 times, because 220 is roughly 1 million. |
| Sam | That is wild. You just replaced a worst case scenario of 1 million sequential comparisons with a guaranteed maximum of 20 comparisons, |
| Alex | and the scaling is where it truly shines. If your data set grows from a million to a billion items, a linear search jumps from 1 million steps to 1 billion steps. A binary search jumps from 20 steps to just 30 |
| Sam | steps. 30 steps to search a billion records. It’s hard to overstate how much of a lifesaver that is when you’re staring at a pipeline that’s been running for 3 hours. |
| Alex | Definitely. But let me ask you about the failure state here. You mentioned the data has to be sorted. What happens if I make a mistake and run a binary search on an unsorted list? Does Python throw a loud error and stop the execution? |
| Sam | No. And that is what makes it so incredibly dangerous in production. It fails completely silently. |
| Alex | Wait, really? It just silently fails? Yeah, |
| Sam | the algorithm is blindly looking at a middle item and throwing away half the list based on a totally meaningless comparison. It will return a false negative simply reporting that your target is not there without generating a single error log. |
| Alex | It’s terrifying. In an automated data pipeline, a silent failure corrupts your analytics without you even knowing your data’s missing. |
| Sam | Exactly. So sorting is mandatory, but you know, sorting algorithms aren’t computationally free. What |
| Alex | is the actual price we pay to unlock this 30-step billion record search? |
| Sam | Sorting a list generally costs about n times the base two logarithm of n comparisons. For a million items, that’s roughly 20 million steps of upfront computational work. |
| Alex | So if I just need to find one thing, |
| Sam | then it’s a terrible idea. The rule of thumb in data science is this if you only need to look up one single item, sorting the entire massive list first is a profound waste of compute. Just take the hit and do a linear search. Makes sense. But If you need to execute a few dozen lookups, the sort has already paid for itself. You pay that heavy computational toll once and every subsequent search is virtually instantaneous. |
| Alex | And for the grad students listening, you’ll generally implement this in Python using the standard library called bisect, and the architecture of bisect is brilliant, specifically a function called bisect left. |
| Sam | Yeah, because instead of just returning a boolean, true or false to say if the item was found. It returns the insertion point, |
| Alex | right? It tells you the exact index position where your target is currently located, or if it’s missing, the exact position where it would need to be inserted to maintain the sorted order of the list, |
| Sam | which opens up a fantastic trick for time series analytics. You can use those insertion points to execute instant range queries. Oh, |
| Alex | absolutely, yeah. Imagine you have a massive sorted list containing millions of transaction timestamps. Your manager wants to know exactly how many transactions occurred between January 1st, 2019 and January 1st, 2020. |
| Sam | You definitely don’t iterate through the data for that. No. |
| Alex | You just use bissect left to find the insertion point for the 2019 date and bisect left again for the 2020 date. Then you simply subtract the smaller index from the larger one, |
| Sam | and you instantly have the exact count of records within that year without ever actually inspecting the data between those dates. |
| Alex | It’s an incredibly elegant solution. You just fence off a massive chunk of data in a fraction of a millisecond. |
| Sam | Yeah, but here’s where it gets really interesting though. Binary search is fast, 30 steps for a billion items. It’s a massive optimization, but it still requires searching. You still have to sort the data beforehand and you still have to actively move fences around to narrow down the location. |
| Alex | So what’s the alternative? What if we could bypass the concept of searching entirely? |
| Sam | That brings us to the radical leap of hashing. The paradigm shift here is abandoning the idea of searching a collection and replacing it with direct mathematical computation. OK. |
| Alex | Think of it like a cloakroom at a fancy theater. You check your coat, the attendant puts it on a hook and hands you a ticket with a random looking number on it. But the cloakroom operates on a secret internal system, |
| Sam | right? The last two digits of your ticket number are the exact number of the hook holding your coat. |
| Alex | Exactly. When you return at the end of the night, they don’t scan the racks sequentially. They don’t sort the codes and do a binary search. They look at your ticket, see it ends in 42, and walk directly to hook 42. 0 searching required. |
| Sam | In Python, that cloakroom architecture is exactly what powers the dictionary or dict and the set. These are hash tables. |
| Alex | And the secret internal system the attendant uses. |
| Sam | That is a hash function. It takes your key, whether that’s a string, a customer ID or a tuple, and runs it through a specific mathematical formula to convert it into an integer. |
| Alex | Let’s ground that. What does that math actually look like under the hood? |
| Sam | A standard approach is to loop through the characters of your key. For each character, the function multiplies a running value by a prime number, often 31, adds the numerical byte value of the character, and then crucially uses a modulo operator against a massive prime number like 17. |
| Alex | OK, let’s clarify that modulo operator for a second. Essentially, it acts as a boundary, right? It takes this wildly massive, unique number generated by all that multiplication. And folds it down so it fits perfectly within the current physical memory limits of your table. |
| Sam | Exactly. It basically says, OK, based on this math, this key absolutely belongs in bucket number 42. |
| Alex | So to look something up, Python just runs the math on the key, gets the number 42, and reaches directly into bucket 42 in memory. Wait, if the modulo operator is folding massive numbers down into a limited number of buckets. What happens if the math for two completely different keys happens to spit out the number 42? |
| Sam | Aha. That is called a hash collision, and it is a statistical certainty when two different keys are mathematically assigned to the same bucket. Python handles it by creating a very short list inside that specific bucket, |
| Alex | which means ironically, if your hash table gets too full, you’re forced right back into doing a linear search to find your item within that tiny list in the bucket. |
| Sam | That is a vital point. The magic of a hash table relies entirely on those internal lists remaining tiny. That’s why Python monitors the table’s load factor, which is the ratio of stored keys to available buckets so aggressively. When the cloakroom gets too full and collisions start forcing those dreaded linear searches, Python automatically pauses execution, doubles the total number of buckets in memory, and recomputs the hash for every single item to spread them all back out. Oh |
| Alex | wow. So as long as Python manages that load factor. The end result is that a lookup in a dictionary or a set takes roughly one computational step. |
| Sam | Yes, in big O notation, that is 0 of 1 or constant time. It does not matter if your data set contains 100 rows or a billion rows. Writing. 9999999 in a set of a million is thousands of times faster than running that same syntax against a list. |
| Alex | It is the ultimate optimization for exact match lookups. |
| Sam | It really is. |
| Alex | Let me play devil’s advocate here though. If dictionaries and sets give us magical one-step lookups, why do we even bother with lists? Why do we ever bother sorting data and using bisect? Why isn’t literally every data structure in Python just a massive hash table? |
| Sam | Well, if we connect this to the bigger picture, it’s because hash tables enforce strict, unforgiving rules in exchange for that speed. The first rule is that your keys must be immutable. They absolutely cannot change over time. |
| Alex | Wait, so if I check my coat, get my ticket, and then alter the numbers on my ticket with a pen, the whole system breaks down. |
| Sam | The system fails completely because the bucket location is computed directly from the exact contents of the key. If a key’s data changes after it has been stored, its mathematical hash changes. Oh, I see. Yeah, so it is now permanently trapped in the wrong bucket, and the algorithm will never find it again. That is why you can safely use strings, numbers, or toss as dictionary keys, but you can never ever use a mutable object like a Python list as a key. OK, |
| Alex | immutable keys make sense. What is the second rule? |
| Sam | A hash table inherently has zero order. Remember, the hash function’s entire purpose is to scatter data pseudo randomly across memory to avoid collisions. |
| Alex | So a dictionary can instantly verify if one specific key is present, but It cannot tell you what key comes next. |
| Sam | Exactly. It cannot tell you what values lie between two dates or which names start with a specific prefix. The concept of sequence is entirely destroyed by the hash function. All right, |
| Alex | so to synthesize our toolkit, |
| Sam | we have standard lists for simple unordered storage where we just need to iterate. We have sorted lists and binary search for range queries, and we have dictionaries and sets for lightning fast exact match lookup. |
| Alex | That’s the toolkit. Let’s move this out of the theoretical. How do we actually apply this in the messy real world scenarios you’ll face as data scientists? |
| Sam | Well, let’s start with a foundational task matching two files, which is essentially a database join. Imagine you inherit a massive, messy CSV containing 900,000 user reviews or tips, but the tips file only contains an internal business ID. To make this data readable for a dashboard, you need to map those 900,000 tips to a separate master file of 150,000 actual business records to get the restaurant names. |
| Alex | This is exactly the mechanical problem pandas.merge is solving under the hood. If you approach this naively and just write a nested loop iterating through the 900,000 tips and doing a linear scan of the 150,000 businesses every single time to find a match, you are looking at over 130 billion comparisons. Yeah, |
| Sam | that script will run for a solid 15 minutes before you see any output. |
| Alex | But if you change your strategy and sort the business IDs first, you can use binary search. That 15-minute pipeline drops to under a single second. |
| Sam | And if you go a step further and build a dictionary mapping the IDs to the business names, the execution time drops to 25 of a second. |
| Alex | Going from 15 minutes to 1 2nd is the difference between a pipeline being fundamentally broken and being usable. Dropping to 0.25 of a second is just optimizing for server cost, but it perfectly illustrates why libraries like Panda’s are so incredibly fast. They are heavily utilizing these exact hash tables internally to execute joins. |
| Sam | Let’s look at another scenario, data quality checks. You need to identify orphan records in your data set. These would be user tips that reference a business ID that doesn’t actually exist in your master business file. |
| Alex | We know from our breakdown of linear search that looking for things that are missing is the absolute worst case scenario. It forces the maximum number of steps every single time. |
| Sam | Exactly. If you use a list for your master business file, verifying those missing records could take hours. But by converting your master business file into a Python set, you reduce the lookup time to constant time. |
| Alex | A simple list comprehension, checking if ID not in set of businesses transforms an hours-long computational bottleneck into a cheap routine check that runs in seconds. You could afford to run it every single time new data enters the pipeline. What about the prefix problem though? So let’s say marketing wants to know how many businesses in our database start with the word star. This is where you have to respect the limitations of the data structures. A dictionary. It is completely useless for a prefix query. You cannot ask a scattered cloakroom for a partial match |
| Sam | because the math requires the full exact string to compute the bucket. |
| Alex | Precisely. To answer a prefix query efficiently, you have to sort the data alphabetically and then use two binary searches to fence in the range, finding where star begins and where it ends. |
| Sam | I want to pause on that because this explains a massive concept in database engineering. This limitation of hash tables is exactly why relational databases like PostgressQL maintain both hash indexes for lightning fast exact matches and sorted B tree indexes for range and prefix queries. |
| Alex | Oh, and those B trees are essentially highly optimized multi-level versions of the binary search trees we just talked about, right? |
| Sam | Exactly. Different analytical questions demand different invisible mechanics. You are matching the internal algorithm to the specific nature of the query, |
| Alex | so. What does this all mean? Like, what is the most practical, immediate takeaway for a data scientist listening to this? |
| Sam | I’d say it is this. If you inherit a script or a Jupiter notebook that used to run in 10 seconds, but now takes an hour because the data volume grew, immediately look for a loop. |
| Alex | Look for an if x in collection statement inside that loop where the collection is a standard list. Simply wrapping that target list in a set command right before the loop begins is often a one-line fix that will collapse the runtime from an hour back down to seconds. |
| Sam | It is a phenomenal debugging heuristic. You just have to ask yourself, how does the computational work grow as the data scales for tiny data sets, lists are perfectly fine. If you need to query ranges or prefixes, you must sort the data and utilize binary search. And if you are doing exact key matching or grouping, you need the constant time of a dictionary or a set. |
| Alex | It fundamentally comes down to choosing the right structural tool for the specific analytical job. But before we wrap up this deep dive, there is one provocative thought I want to leave you with, something to heavily consider as you write pipelines this semester. |
| Sam | What’s that? |
| Alex | All of these computer science theories, all of these optimizations. They focus almost entirely on time complexity. How many steps does a lookup take? Can we force it down to constant time? |
| Sam | Right? Time is universally treated as the primary metric for optimization. But what about |
| Alex | the memory cost? When you take a massive million row list and convert it into a dictionary or a set to make your lookups instant. You’re fundamentally trading memory space for execution speed. |
| Sam | Oh, that’s a great point. Remember how hash tables have to build extra buckets, scatter the data, and strictly manage that load factor so things don’t collide. They leave empty space and memory on purpose. |
| Alex | They do. They are incredibly memory hungry data structures. Yeah, |
| Sam | so in modern data science, when you are working with massive pandas data frames on cloud instances with hard RAM limits, you have to ask yourself at what point does optimizing purely for execution time accidentally bankrupt your server’s memory? |
| Alex | Because speed is amazing, but it isn’t free. If you blindly cast a 50 million row pandas column to a set just to save a few seconds of compute time, you might trigger an out of memory crash that takes down the entire system. |
| Sam | It is entirely about balancing those constraints. Deeply understanding the underlying machinery is what allows you to weigh those trade-offs intelligently rather than just guessing. |
| Alex | You have to know what is actually behind the door before you choose to open it. Are you stepping into a highly optimized filing cabinet or a chaotic memory-heavy pile? The Python code looks identical on the surface, but now you know how to visualize the mechanics operating underneath. Thanks for diving deep with us today. |
Presentation
Read
- Search and Hashing (lecture notes)
Hands-on
Notebooks in 11-Search-Hashing
Homework
- Homework 10: Three Ways to Find It — due Wednesday, November 18, 2026