-1

say that I have a nested list like this for example:

List = [['a','d','b'],['a','x','w','t','d'],['g','c','d','z']]

and what I want to do is find the object in the List that all the smaller lists share, so for the example List I gave 'd' would be the object they all share.

here is what I have done so far:

def related(List):
    for item in List[0]:
      for i in range(1, len(List)):
        if item in List[i]:
            return item

the problem I am having is that when I do:

related([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])

'a' is returned, but that isn't the correct answer since 'a' isn't in all the lists and only in the first 2 lists. The correct answer with that list should be 'd'.

My function basically just stops running once it finds the same object in just 1 of the lists.

Will someone be able to send me towards the right path on what I can do to get my code working correctly? Thank You!!!

Joe
  • 35
  • 1
  • 9
  • 1
    Add a counter and increment it every time your element is in a sublist. If the total value of counter equals the number of sublists, then it should return the element. – Vasilis G. Dec 04 '17 at 20:43
  • The issue with your current approach is that your function short-circuits as soon as it finds a value from the first sublist in any other list. – miradulo Dec 04 '17 at 20:47

1 Answers1

3

What you're looking for here is the intersection of these lists. Python lists don't have an intersection functionality built-in, but sets do. We can do

def in_common(l):
    if not l:
        return set()
    return set(l[0]).intersection(*l[1:])

This converts the first element to a set, and then finds the intersection of that set with the rest of the elements in the list.

in_common([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])

returns

{'d'}

the set containing 'd'

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96