listl = [] listr = [] with open("input") as lines: for line in lines.readlines(): line = line.rstrip() print(line) spli = line.split(" ") listl.append(int(spli[0])) listr.append(int(spli[-1])) assert len(listl) == len(listr) listl.sort() listr.sort() dtot = 0 for i in range(len(listl)): l = listl[i] d = listr.count(l) * l dtot += d print(l, d) print(dtot)