8

There are some things wrong when i try to delete an element of a list by using function Nothing. Here is a simple example:

{a = Range[10], a[[1]], a[[1]] = Nothing, a}(*{{1,2,3,4,5,6,7,8,9,10},1,{2,3,4,5,6,7,8,9,10}}*)

It works,but when i try it again.

{a[[1]], a[[1]] = Nothing, a}(*{2,{2,3,4,5,6,7,8,9,10}}*)

It doesn't work.Finally i found that the first element of a could be deleted if i evaluate the code a[[2]]=Nothing,Any answer will be most appreciated

Lukas Lang
  • 33,963
  • 1
  • 51
  • 97
Ren Witcher
  • 707
  • 3
  • 12

2 Answers2

12

Taking a look at ?a shows what's going on:

?a

(* Global`a *)

(* a={Nothing,2,3,4,5,6,7,8,9,10} *)

It seems that Part ([[...]]) does not apply the effect of Nothing after the replacement has been done, leaving you with a list that is still 10 elements long. So the second a[[1]]=... simply replaces the Nothing in the first element with Nothing again.

You case use Delete to do the deletion properly:

{a = Range[10], a[[1]], a = Delete[a, 1], a}
(* {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, {2, 3, 4, 5, 6, 7, 8, 9, 
  10}, {2, 3, 4, 5, 6, 7, 8, 9, 10}} *)

{a[[1]], a = Delete[a, 1], a}
(* {2, {3, 4, 5, 6, 7, 8, 9, 10}, {3, 4, 5, 6, 7, 8, 9, 10}} *)
Lukas Lang
  • 33,963
  • 1
  • 51
  • 97
  • Thank you for the answer!i get it. – Ren Witcher Sep 27 '19 at 12:20
  • Interesting that {a, b, Nothing, c, d, Nothing}; (* new line *) % // Length gives 4. – Markhaim Sep 27 '19 at 12:24
  • 4
    @Markhaim That happens because the list gets evaluated and after evaluation the Nothings will have disappeared. If you compare Length[Unevaluated[{1, Nothing, 3}]] with Length[{1, Nothing, 3}], you'll see the same effect. – Sjoerd Smit Sep 27 '19 at 14:25
11

Part assignment performs in-place modification of an expression without evaluation of the result. At the same time, on the Documentation page for Nothing we read:

Nothing is removed as part of the standard evaluation process.

So after evaluation of a[[1]] = Nothing you still have a List of length 10 with first element being Nothing. You can replace Nothing with anything else in the same way again:

a[[1]] = Nothing;
Definition[a]
a[[1]] = Missing[];
Definition[a]
a={Nothing,2,3,4,5,6,7,8,9,10}

a={Missing[],2,3,4,5,6,7,8,9,10}

You can remove Nothing by evaluating the expression:

a[[1]] = Nothing;
Definition[a]
a = a;
Definition[a]
a={Nothing,2,3,4,5,6,7,8,9,10}
a={2,3,4,5,6,7,8,9,10}

Instead of Nothing you can use such functions as Delete, Drop, Take or ReplacePart for the same purpose.

Alexey Popkov
  • 61,809
  • 7
  • 149
  • 368