def substrings(a, b, n): """Return substrings of length n in both a and b""" line_a =  i = 0 while i + n < len(a): sub_a = a[i:i+n] line_a.append(sub_a) i += 1 line_b =  j = 0 while j + n < len(b): sub_b = b[j:j+n] line_b.append(sub_b) j += 1 set_a = set(line_a) set_b = set(line_b) set_end = set_a&set_b line_end = list(set_end) return line_end
This is one of the rare cases where you might need
i + n <= len(a) instead of
<. Same for the other condition.
i+n in the slice syntax is the first character that's not part of the slice, so that one has to be
len(a) in the last iteration.
BTW, it might have been helpful if you had told us how this code misbehaves. Just dropping the code is not nice. See Why questions don't get answers or why people are ignored? section "THE (NAKED) CODE DROP"