Check if two iterables are permutations of each other

Python, List, String · May 23, 2023

Check if two iterables are permutations of each other.

  • Use len to check if both iterables have the same length.
  • Use Counter to verify that each element appears an equal number of times in both iterables.
from collections import Counter

def is_perm(items0, items1):
  return len(items0) == len(items1) and Counter(items0) == Counter(items1)
is_perm([1, 2, 3], [4, 1, 6]) # False
is_perm([1, 2], [2, 1]) # True

is_perm("dad", "add") # True
is_perm("snack", "track") # False

More like this

  • Python Strings

    Learn how to format and manipulate strings in Python 3.6 with this snippet collection.

    Collection · 27 snippets

  • 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

  • List symmetric difference based on function

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

    Python, List · Nov 2, 2020

  • List difference

    Calculates the difference between two iterables, without filtering duplicate values.

    Python, List · Nov 2, 2020