 # Is there a better way to find unique lists within nested lists than this code

The following works but I’m wondering if there is a better more Pythonic way. I’m checking if there is any list in `crosses` that has all different numbers than any list in `crosses` then check `crosses` vs `crosses`, then check `crosses` vs `crosses`, and so on. The list might be much longer I just used a short one for example.

The lists that do not share any of the same numbers are:

``````crosses and crosses,
crosses and crosses,
crosses and crosses
``````
``````crosses = [[[1,2,3,4], [2,3,4]], [[1,6,7,8], [2,6,7,8]], [[1,2], [6,7]]]
result = 0
for i in range(len(crosses)):
for j in range(len(crosses[i])):
for k in range(i + 1, len(crosses)):
for l in range(len(crosses[k])):
match = False
for num in crosses[i][j]:
if num in crosses[k][l]:
match = True
if not match:
area = len(crosses[i][j]) * len(crosses[k][l])
if area > result:
result = area
print(result) # 12
``````

You could try using sets and set operations to simplify checking for matching elements between two sets (lists).

So, basically create a set from the two lists being compared and if the length of the set is less than the total length of the two original lists added together then there is overlapping numbers in the lists. Is that what you’re thinking? That did cross my mind and I wondered about time complexity. I’ve studied time complexity and get the “gist” of it but I have to admit not fully grasped it.

That’s one way. I was thinking more about getting intersection of two sets (two lists) and checking if the resulting set is empty (meaning there’s no matching elements in both lists) or not.

Regarding the time complexity - is there a specific concern? If not I’d just stick with what is more clear for you. Step with making sets might add some overhead, but checking if two sets have matching elements should be much faster than iterating manually over the contents of the lists. Generally due to how sets work, checking if element is in set is as fast as it gets. The more elements are in the initial set (list), the more advantage will have set.

1 Like

Thanks for the reply, I’ll look more into sets and intersection and see if I can shorten it up a bit.

This code was part of a solution I had for a hackerrank challenge, my solution passed the test in the time limit but it got me thinking if the lists were nested deeper I would need to add more loops and if the data is really large would my code be the most efficient?