Home > OS >  How to know if lists inside list contain the same elements
How to know if lists inside list contain the same elements

Time:09-16

Is there a way to know if the lists inside a list contain the same elements with python?

For example:

Return True if given list [['A', 'B'], ['A', 'B'], ['A', 'B']] or False if given list [['B', 'C'], ['Z', 'C']]

CodePudding user response:

You can use set which only contains unique value

l = [['A', 'B'], ['A', 'B'], ['A', 'B']]
def find_uniqueness(l):
  l = set(tuple(row) for row in l)
  if len(set(l)) <= 1:
    print("Same data")
    return True
  else:
    print("Multiple unique data")
    return False

find_uniqueness(l)

CodePudding user response:

You can try:

same_elements_exist = len({tuple(e) for e in lst}) <= 1

Note that it considers the order of the elements while comparing.

If you don't need to consider order then do sorted

same_elements_exist = len({tuple(sorted(e)) for e in lst}) <= 1

CodePudding user response:

Converting the sub-lists to tuples and then putting them in a set, as answers from @PrakashDahal and @SomeDude are, may make the code appear to be concise and clever, but is inefficient if either the sub-lists or the main list is long since the tuple conversion and set creation do no benefit from any short-circuiting when there are any items that are different.

Instead, get the first sub-list from the list and then iterate through the rest of the list to validate that all of the sub-lists are equal to the first sub-list. If at any point any sub-list is found to be different, the iteration would end and not waste time validating the rest of the list. Any sub-list can be found different if any item is different from the corresponding item in the first sub-list when iterating through each sub-list, so it benefits from short-circuiting there as well:

def is_same(lst):
    if not lst:
        return True
    seq = iter(lst)
    first = next(seq)
    return all(i == first for i in seq)
  • Related