Message Boards Message Boards

0
|
3369 Views
|
3 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Remove elements from a list for getting new list ?

Posted 4 years ago

Hi,

How do I remove elements from my list for generating a new list like below:

list = {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, w};

listNEW = {a, e, i, m, q, w}

enter image description here

POSTED BY: Alex Teymouri
3 Replies
Posted 4 years ago

Hi Alex,

If the elements to be removed are position based rather than value based then

list[[1 ;; -1 ;; 4]]
(* {a, e, i, m, q, w} *)

If value based then, unless there is some way to programmatically select the values, the list has to be constructed by hand

Complement[list, {b, c, d, f, g, h, j, k, l, n, o, p, r, s, t}]
(* {a, e, i, m, q, w} *)
POSTED BY: Rohit Namjoshi
Posted 4 years ago

Also look at DeleteCases.

POSTED BY: Joel Klein
Posted 4 years ago

Hi Joel,

Thanks for pointing out DeleteCases. Important if order needs to be preserved. Similar to Union and DeleteDuplicates.

DeleteCases[list, Alternatives @@ {b, c, d, f, g, h, j, k, l, n, o, p, r, s, t}]

or

DeleteCases[list, x_ /; MemberQ[{b, c, d, f, g, h, j, k, l, n, o, p, r, s, t}, x]]

will preserve the order but Complement will not, the result is sorted.

Complement[Reverse@list, {b, c, d, f, g, h, j, k, l, n, o, p, r, s, t}]
(* {a, e, i, m, q, w} *)

DeleteCases[Reverse@list, x_ /; MemberQ[{b, c, d, f, g, h, j, k, l, n, o, p, r, s, t}, x]]
(* {w, q, m, i, e, a} *)
POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract