WolframLang: Delete Element in List
Delete by Index Range
Drop[ expr, n]
-
Drop 1st to nth
Drop
Drop[ {1, 2, 3, 4, 5}, 3 ] === {4, 5}
Drop[ expr, -n]
-
Drop nth to last.
Drop[ {1, 2, 3, 4, 5}, -3 ] === {1, 2}
Drop[ expr, {n}]
-
Drop just nth.
Drop[ {1, 2, 3, 4, 5}, {3} ] === {1, 2, 4, 5}
Drop[ expr, {m,n}]
-
Drop mth to nth.
Drop[ {1, 2, 3, 4, 5}, {2,4} ] === {1, 5}
Delete by Position
Delete[expr, n]
-
if n is a integer, consider it as
position spec
{n}
. Result is same asDelete[expr, {n}]
andDelete[expr, {{n}}]
x = {a, {{b, c}, d}, e}; Delete[ x, 1 ] === {{{b, c}, d}, e} Delete[ x, {1} ] === {{{b, c}, d}, e} Delete[ x, {{1}} ] === {{{b, c}, d}, e}
Delete[expr, {pos1, pos2, pos3 etc}]
-
Delete a list of elements by Position
Delete
x = {a, {{b, c}, d}, e}; Delete[ x, {{1}} ] === {{{b, c}, d}, e} Delete[ x, {{2}} ] === {a, e} Delete[ x, {{1}, {2}} ] === {e} Delete[ x, {{2, 1}} ] === {a, {d}, e} Delete[ x, {{2, 1, 1}} ] === {a, {{c}, d}, e}
Delete by Pattern
DeleteCases
-
Delete elements by Pattern
DeleteCases
DeleteCases[ {1, 3, 2, 4}, 2 ] === {1, 3, 4} DeleteCases[ {a, b, c}, c ] === {a, b} DeleteCases[ {a, f[3], c}, f[3] ] === {a, c} DeleteCases[ {a, f[3], g[4], f[5]}, f[_] ] === {a, g[4]} DeleteCases[ {{2}, {4, 8}, {c}}, {_ , _} ] === {{2}, {c}}
Delete Duplicates
DeleteDuplicates[expr]
-
Delete duplicates
DeleteDuplicates
DeleteDuplicates[ {3, x, 3, x, 4 } ] === {3, x, 4}
the Nothing element
Nothing
-
when a list element is changed to
Nothing
, it is removed in a list. Nothing{3, Nothing, 4} === {3, 4}
The
Nothing
is not removed when Head is not List.f[3, Nothing, 4] (* f[3, Nothing, 4] *)
This is sometimes very convenient way to delete element, especially when you are mapping a function over a list. [see Map Function to List]
(* remove odd by replace it with Nothing *) Map[ If[ OddQ[ # ] , Nothing , # ]&, {1, 2, 3, 4, 5, 6} ] === {2, 4, 6}