Comparing lists of PartDefinitions

Hello, I was wondering if there’s a simple way to compare two lists of syside elements (for example syside.core.PartDefinition) that returns the diff? My usual approaches like:

  • list(set(list1) - set(list2))
  • x for x in list1 if x not in list2

don’t seem to be working..

Thank you!

Tom

Hi,

I have a hard time understanding what the expected behaviour is. Can you provide more details such as inputs, e.g. source snippets, and an expected output?

There is no deep equality for elements as each element is unique, the equality is effectively an identity check.

Here’s what I ended up doing last night, very likely not the most elegant solution.. but it gets the job done for now.

Inputs: Two lists of parts (which have been generated from the model by analyzing in which use contexts they have been used).

Intended outcome: Basically a classification of the parts into three categories: Parts that are present in both lists, list1, and list2 (like a Venn diagram).


    # Get Part Names
    list1_part_names = [part.name for part in parts_list1]
    list2_part_names = [part.name for part in parts_list2]

    # Remove duplicates
    list1_part_names = list(dict.fromkeys(list1_part_names))
    list2_part_names = list(dict.fromkeys(list2_part_names))

    # Convert to sets
    list1_names = set(list1_part_names)
    list2_names = set(list2_part_names)

    for name in list1_names :
        if name not in list2_parts_names :
            print(f"{name} is present in list1 but not in list2.")

    for name in list2_names :
        if name not in list1_parts_names :
            print(f"{name} is present in list2 but not in list1.")  

Parts can be compared by equality, rather than by .name. The latter (.name) need not be uniquely defining, as two parts may have the same name, as long as they are defined in different places.

If you do not care about their order, you can simply work directly with set operations:

part_set1 = set(part_list1)
part_set2 = set(part_list2)

only_in_1 = part_set1.difference(part_set2)
only_in_2 = part_set2.difference(part_set1)
in_both = part_set1.intersection(part_set2)
1 Like

To add to what @Daumantas said, if you want to compare elements by what they represent rather than identity, I would suggest using qualified_name as it is more robust than name alone (two elements in different packages can share the same name, but will always have distinct qualified names):

# Build sets of qualified names for comparison
list1_qualified_names = {str(p.qualified_name) for p in parts_list1}
list2_qualified_names = {str(p.qualified_name) for p in parts_list2}

# Venn diagram classification using set operations
only_in_list1 = list1_qualified_names - list2_qualified_names
only_in_list2 = list2_qualified_names - list1_qualified_names
in_both = list1_qualified_names & list2_qualified_names
1 Like

Thank you all! A much more elegant solution! :slight_smile: