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
  • 34,719
  • 24
  • 185
  • 251
user3056783
  • 1,723
  • 1
  • 22
  • 44

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
  • 963,270
  • 265
  • 3,804
  • 3,187