Pythonic Nested for - loops in Python
I am working on this code where I have nested for loops. a_list and b_list are list of tuples, where each tuple is made up of two tensors [(tens1, tens2), ...]. I am trying to compute the similarity of every tens1 in a_list to every tens1 in b_list. Below is the code I have. And the nested loop appears to be a bottleneck. Is there a better way(pythonic) that I can re-write the loops?

a2b= defaultdict(dict)
b2a= defaultdict(dict)
ab_sim = []

for a, vec_a in a_list:
    for b, vec_b in b_list:
        # Ignore combination if the first element in both a and b are same
        if a[0] == b[0]:
            continue
        # Calculate cosine similarity of combination
        sim = self.calculate_similarity(vec_a, vec_b )
        a2b[a][b] = sim
        b2a[b][a] = sim
        ab_sim.append(sim)


The calculate_similarity is just a method computing cosine similarity. a_list and b_list could be of any size. I have b2a and a2b because I need them for other computations.

You could use a dictionary comprehension:

a2b = {a: {b: self.calculate_similarity(vec_a, vec_b )
       for (b, vec_b) in b_list if a[0] != b[0]} for (a, vec_a) in a_list}

