 <p>I have set up a simulation here and comments will describe the steps.</p> <p>First I generate some data: a series of tuples each containing a string and two random numbers representing score A and B.</p> <p>Next I divide the ranges of A and B into five equally spaced bins, each representing the minimum and maximum for a cell.</p> <p>Then I serially query the data set to extract the strings in each cell.</p> <p>There are a hundred ways of optimizing this, based on the actual data structure and storage you are using.</p> <pre><code>from random import random # Generate data and keep record of scores data = [] a_list = [] b_list = [] for i in range(50): a = int(random()*500)+1 b = int(random()*500)+1 rec = { 's' : 's%s' % i, 'a' : a, 'b' : b } a_list.append(a) b_list.append(b) data.append(rec) # divide A and B ranges into five bins def make_bins(f_list): f_min = min(f_list) f_max = max(f_list) f_step_size = (f_max - f_min) / 5.0 f_steps = [ (f_min + i * f_step_size, f_min + (i+1) * f_step_size) for i in range(5) ] # adjust top bin to be just larger than maximum top = f_steps[4] f_steps[4] = ( top[0], f_max+1 ) return f_steps a_steps = make_bins(a_list) b_steps = make_bins(b_list) # collect the strings that fit into any of the bins # thus all the strings in cell[4,3] of your matrix # would fit these conditions: # string would have a Score A that is # greater than or equal to the first element in a_steps[3] # AND less than the second element in a_steps[3] # AND it would have a Score B that is # greater than or equal to the first element in b_steps[2] # AND less than the second element in a_steps[2] # NOTE: there is a need to adjust the pointers due to # the way you have numbered the cells of your matrix def query_matrix(ptr_a, ptr_b): ptr_a -= 1 from_a = a_steps[ptr_a][0] to_a = a_steps[ptr_a][1] ptr_b -= 1 from_b = b_steps[ptr_b][0] to_b = b_steps[ptr_b][1] results = [] for rec in data: s = rec['s'] a = rec['a'] b = rec['b'] if (a &gt;= from_a and a &lt; to_a and b &gt;= from_b and b &lt; to_b): results.append(s) return results # Print out the results for a visual check total = 0 for i in range(5): for j in range(5): print '=' * 80 print 'Cell: ', i+1, j+1, ' contains: ', hits = query_matrix(i+1,j+1) total += len(hits) print hits print '=' * 80 print 'Total number of strings found: ', total </code></pre>