I have a few lists, each containing several cities. I need to check for any two random elements if they belong to the same list.
Simple example:
list1 = ['London', 'Manchester', 'Liverpool', 'Edimburgh']
list2 = ['Dublin', 'Cork', 'Galway']
list3 = ['Berlin', 'Munich', 'Frankfurt', 'Paris', 'Milan', 'Rome', 'Madrid', 'Barcelona', 'Lisbon', ...]
list4 = ['Washington', 'New York', 'San Francisco', 'LA', 'Boston', ...]
Expected results:
> in_same_group('London', 'Liverpool')
> True
>
> in_same_group('Berlin', 'Washington')
> False
The function is called very often, so speed is critical. The biggest list might have up to 1000 elements.
What would be the most efficient way to do it?
This is what I tried so far, but it is far too slow:
def in_same_group(city1, city2):
same_group = False
for this_list in [list1, list2, list3...]:
if city1 in this_list and city2 in this_list:
return True
return same_group