john
john

Reputation: 81

Python comparing three lists with different lengths

I am trying to compare three different lists each with a potentially different length to the others but I'm not exactly sure how to do this. Originally I thought to just get the largest list length but then realized if the others are less then it will try find empty elements and return an error. I am trying to find if all the lists have a common element

Currently I have:

for i in range(n) //n is largest list length
    if (listA[i] in listB) and (listA[i] in listC):
        common = True
    else:
        common = False

If possible, could you give an answer where it can be applied to numerous lists rather than be limited to three

Upvotes: 1

Views: 1072

Answers (1)

user2390182
user2390182

Reputation: 73450

You can get all common elements of all 3 lists using set intersection:

intersection = set(listA) & set(listB) & set(listC)
common = bool(intersection)  # True if not empty

A contains-checks on two lists in a loop has time complexity O(A*(B+C)) (quadratic). This is O(A+B+C) (linear).

If the entire intersection is more info than you need, you can still do the following and benefit from an early break:

setBC = set(listB) & set(listC)
common = any(x in setBC for x in listA)

Upvotes: 6

Related Questions