# Removing specific entries from a list

I have the list

L=8;
indx = Range[-π, π, 2 π/L]
(* {-π, -((3 π)/4), -(π/2), -(π/4), 0, π/4, π/2, (3 π)/4, π} *)


Now I want to delete specific elements of this list, e.g -(π/2), 0, (3 π)/4

I make a new list which includes the values I wish to delete, i.e:

exvals={-(π/2), 0,  (3 π)/4};


and

For[i = 1, i <= Length[exvals], i++, indx = DeleteCases[indx, exvals[[i]]]]
indx
(*={-π, -(π/2), -(π/4), π/4, (3 π)/4, π} *)


which works fine. I am wondering if there is a more compact way to do it without using For

• DeleteCases[indx, exvals] (should not change sorting order) or Complement[indx, exvals] (will return sorted list). Jan 3, 2021 at 19:11
• also DeleteCases[Alternatives @@ exvals]@indx.
– kglr
Jan 3, 2021 at 19:14
• Thanks @MarcoB. I was not aware of Complement. Please post it as a reply
– geom
Jan 3, 2021 at 19:15
• @kglr Thanks. Your suggestion also works fine.
– geom
Jan 3, 2021 at 19:17

Two ways come to mind, which have different consequences on the ordering of the results. To show that, let me create a scrambled version of your list, so it is not ordered in numerical value:

L = 8;
indx = Range[-π, π, 2 π/L];

SeedRandom[20210103]
scrambled = RandomSample[indx]

(*Out: {π, π/2, -((3 π)/4), -(π/2), (3 π)/4, -π, -(π/4), π/4, 0} *)


You can then use DeleteCases or Complement to achieve functionally similar results, but with or without sorting the output, respectively:

DeleteCases[scrambled, Alternatives @@ exvals]
(* Out: {π, π/2, -((3 π)/4), -π, -(π/4), π/4} *)

Complement[scrambled, exvals]
(* Out: {-π, -((3 π)/4), -(π/4), π/4, π/2, π} *)

• I should probably also mention the implementation of unsortedComplement[] here. Jan 4, 2021 at 4:50