wolfram-mathematica

Comparing lists in Mathematica


I want to compare two lists in Mathematica, see what elements in the first list are not in, the second list, and then print out the non-equal elements. I generated two lists and I want to use a for loop to go through the two lists and compare each element.


Solution

  • list1 = {3, 56, 9, 8, 7, 33, 5};
    list2 = {33, 4, 56, 7, 9, 23};
    

    The usual idiom would be Complement. Note, it sorts the output.

    notinlist2 = Complement[list1, list2]
    notinlist1 = Complement[list2, list1]
    
    {3, 5, 8}
    {4, 23}
    

    Using a For loop preserves the order from list1

    notinlist2 = {};
    
    For[i = 1, i <= Length[list1], i++,
     If[FreeQ[list2, list1[[i]]],
      AppendTo[notinlist2, list1[[i]]]]]
    
    notinlist2
    
    {3, 8, 5}
    

    The same can be achieved with DeleteDuplicates

    Drop[DeleteDuplicates[Join[list2, list1]], Length[list2]]
    
    {3, 8, 5}