This seems like it would be easy to do with a single dictionary. In this case, I'm not actually making any lists, just identifying which list each item would go in. If you actually do need real list objects, you can add them later, or perhaps store them instead of the a number.
data_str = '''A F
G H
F J
Y G
H G'''
data = [line.strip().split() for line in data_str.splitlines()]
list_ids = {}
next_id = 0
for a, b in data:
if a in list_ids and b in list_ids:
pass # do nothing if they both are already in a list
elif a in list_ids:
list_ids[b] = list_ids[a]
elif b in list_ids:
list_ids[a] = list_ids[b]
else:
list_ids[a] = list_ids[b] = next_id
next_id += 1
for name, id in list_ids.items():
print(name, id)
Note that if you need to handle items that are already in lists by joining the lists (rather than just ignoring pairs that are both already in lists), you're dealing with disjoint sets, which have some pretty nifty algorithms.