0

What is the best way to compare two lists in Python and to check occurrences?

Consider that

list1 = [a, b, c]
list2 = [a, b, c, d, e, f, g]

I need two things:

  • to check if list1 contains elements from list2 and get back True or False
  • to check how many items (len?) from list2 are in list1 and get back integer of those occurrences
Cœur
  • 37,241
  • 25
  • 195
  • 267
user3056783
  • 2,265
  • 1
  • 29
  • 55

1 Answers1

2

You want to use sets here:

intersection = set(list1).intersection(list2)

intersection is now a set of all elements from list1 that also occur in list2. It's length is the number of occurrences.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343