I have the list

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};


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

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

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

1 Answer 1


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];

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, π} *)
  • $\begingroup$ I should probably also mention the implementation of unsortedComplement[] here. $\endgroup$ Jan 4, 2021 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.