# Stopping mathematica from rearranging elements in a list

I have the following list

set1={-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}


How when I am doing

Complement[set1, {-1/x}]


Then it gives

{1, -(1/x) + x/2 - 2 Log[x] - Log[x]/x}


then it rearranges the third element to the second element and vice versa. This is dangerous for my case. How to stop this?

• Complement, Union, Intersection treat the list as a set. Hence duplicates are deleted and a sort is performed.
– Syed
Nov 9, 2023 at 9:48

You can use DeleteElements which came with V 13.1:

set1 = {-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}

DeleteElements[set1, {-1/x}]


Versions prior to 13.1 could use f.e.

Delete[set1, Position[set1, -1/x, 1]]


or (since V 12.1)

SubsetReplace[set1, {-1/x} -> Nothing]


Both give the expected result:

UniqueElements[{set1,{ -1/x}}][[1]]

(* {-x^(-1)+x/2-2*Log[x]-Log[x]/x,1} *)

set1 = {-1/x, -1/x + x/2 - 2 Log[x] - Log[x]/x, 1};

Fold[DeleteCases, set1, {-1/x}]
(*    {-1/x + x/2 - 2 Log[x] - Log[x]/x, 1}    *)


Instead of applying "Complement" to the whole list set1, you may apply it to the single elements of set1 like:

set1 = {-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1};
Complement[{#}, {-1/x}] & /@ set1 // Flatten

{-(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}


or use filter, in Mathematica it's Select

{-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1} //
Select[# =!= -1/x&]


If I understand correctly, this is what you need

set1 = {-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}
SortBy[Complement[set1, {-1/x}], Position[set1, #] &]