4
$\begingroup$

from the following table we have,

Table[i,{i,0,4,1}]

we (0,1,2,3,4)

can we have somehow

(0,2,3,4)

? a formula Table[i-....,{i,....,...}]

$\endgroup$
0

5 Answers 5

8
$\begingroup$

If you want to remove specific entries, there are at least 10 ways to do it. One way could be to insert an If inside the table. Something like

Table[If[i == 1, Nothing, i], {i, 0, 4, 1}]

Mathematica graphics

If you want more general approach, need to give a more general problem. Otherwise, this is very specific problem. You could simply also remove the 1 from the output afterwords?

Help on Nothing says

Nothing represents an element of a list that will automatically be
removed.

$\endgroup$
6
$\begingroup$

With the list

list = {0, 1, 2, 3, 4, 2, 9, 2, 10, 1};

you can combine FirstPosition and Delete

Delete[list, FirstPosition[list, _?(# == 2 &)]]

in order to remove only the first time 2 appears

l1

If you use DeleteCases with Infinity as level specification

DeleteCases[list, 2, Infinity]

you'll remove all instances of 2

l2

$\endgroup$
5
$\begingroup$

Using position with Delete:

Delete[Table[i, {i, 0, 4, 1}], {2}]
(*{0, 2, 3, 4}*)

Using element with DeleteElements:

DeleteElements[Table[i, {i, 0, 4, 1}], {1}]
(*{0, 2, 3, 4}*)
$\endgroup$
3
$\begingroup$

A Sow and Reap method:

Reap[{Do[If[i==1,Continue[]];Sow[i], {i,0,4}]}][[2,1]]

(* {0, 2, 3, 4} *) 

And (for example):

Reap[{Do[If[i==1 || i == 5,Continue[]];Sow[i], {i,0,10}]}][[2,1]]

(* {0, 2, 3, 4, 6, 7, 8, 9, 10} *) 
$\endgroup$
1
  • $\begingroup$ With Scan: Reap[Scan[If[#==1,Nothing,Sow[#]]&]@Range[0,4]][[2,1]] $\endgroup$
    – user1066
    Feb 7, 2023 at 9:04
3
$\begingroup$
list = {0, 1, 2, 3, 4, 2, 9, 2, 10, 1};

To delete all 2s

ReplaceAt[list, 2 :> Nothing, All]

{0, 1, 3, 4, 9, 10, 1}

or, like E. Chan-López showed

DeleteElements[list, {2}]

{0, 1, 3, 4, 9, 10, 1}

To delete only the first 2

DeleteElements[list, 1 -> {2}]

{0, 1, 3, 4, 2, 9, 2, 10, 1}

To delete the first two 2s:

DeleteElements[list, 2 -> {2}]

{0, 1, 3, 4, 9, 2, 10, 1}

or

SubsetReplace[list, {Repeated[2, {2}]} -> Nothing]

{0, 1, 3, 4, 9, 2, 10, 1}

$\endgroup$

Your Answer

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

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