Check lists have same contents

Python, List · Nov 2, 2020

Checks if two lists contain the same elements regardless of order.

  • Use set() on the combination of both lists to find the unique values.
  • Iterate over them with a for loop comparing the count() of each unique value in each list.
  • Return False if the counts do not match for any element, True otherwise.
def have_same_contents(a, b):
  for v in set(a + b):
    if a.count(v) != b.count(v):
      return False
  return True
have_same_contents([1, 2, 4], [2, 4, 1]) # True

More like this

  • List is contained in other list

    Checks if the elements of the first list are contained in the second one regardless of order.

    Python, List · Jan 7, 2021

  • Merge lists

    Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions.

    Python, List · Nov 2, 2020

  • List difference based on function

    Returns the difference between two lists, after applying the provided function to each list element of both.

    Python, List · Nov 2, 2020