0

Is there a way to avoid this for loop in favor of efficiency? I was thinking about iter/next functions but they don't seem to work properly..

def foo():
    lst = [['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['d', 'h', 'i', 'j']]
    res = set(lst[0])
    for word in lst:
        res = res.intersection(word)
    return ''.join(res)
EddyIT
  • 133
  • 6

1 Answers1

2

set.intersection isn't limited to a single argument.

res = set(lst[0]).intersection(*lst[1:])

For example:

>>> foo = set([1,2,3])
>>> foo.intersection([1,2])
{1,2}
>>> foo.intersection([2,3])
{2,3}
>>> foo.intersection([1,2], [2,3])
{3}
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Does `intersection` not expect only `set` arguments? – Guimoute Nov 14 '19 at 17:03
  • 2
    No; the arguments can be any iterables. (The *first*, implicit argument has to be a set, so `set.intersection([1,2], [2,3])` won't work, but `set.intersection(set([1,2]), [2,3])` is the same as `set([1,2]).intersection([2,3])`.) – chepner Nov 14 '19 at 17:04
  • 2
    This question was already answered here: https://stackoverflow.com/questions/3852780/python-intersection-of-multiple-lists – whati001 Nov 14 '19 at 17:05
  • @whati001 So vote to close as a duplicate. – chepner Nov 14 '19 at 17:07
  • Thanks. For some reason I would feel better with something like `set.intersection(*(set(lst) for lst in list_of_lists))`. I don't like the idea needed an "irregular" first element to start the process. – Guimoute Nov 14 '19 at 17:07