TransWikia.com

Null being added to every element in list list

Mathematica Asked by chris.s77 on May 16, 2021

I recently just started using mathematica, and I’m having some trouble figuring out what’s wrong with this. When I run this, the output I get adds Null with every element. I have no idea what I’m doing wrong here. This program is meant to reverse a string without using StringReverse

butterfly[word_] :=
     Module[{wordchar = {}}, 
      For[i = StringLength[word], i > 0, i--, 
        AppendTo[wordchar, StringPart[word, i]
         ]
        ]
       wordchar
      ]
butterfly["abcdef"]

output: {"f" Null, "e" Null, "d" Null, "c" Null, "b" Null, "a" Null}

One Answer

Welcome to MMA SE! So, essentially the problem here is that line breaks don't count for anything inside expressions—only between expressions. So,

a = 4
b = 5

is fine, and is interpreted as two separate inputs;

a = (Echo[3]
5)

is not interpreted as "do Echo, then 5". Within an expression, you need to use ; to separate sequentially-evaluated parts. Otherwise, line breaks, like spaces, are interpreted as Times!

That's relevant here because in the lines

For[i = StringLength[word], i > 0, i--, 
        AppendTo[wordchar, StringPart[word, i]
         ]
        ]
       wordchar

you're essentially multiplying the output of the For loop, which is Null, by the list wordchar. Since multiplication is threaded over lists automatically, you get Null multiplying every string in the list. Check out butterfly["abcdef"] // FullForm to see the Times explicitly!

So, modifying it to

butterfly[word_] :=
     Module[{wordchar = {}}, 
      For[i = StringLength[word], i > 0, i--, 
        AppendTo[wordchar, StringPart[word, i]
         ]
        ];
       wordchar
      ]

should fix it!

Note, however, that For loops are very "non-Mathematica-l"! Generally, you'll want to use Table (or maybe Array, or Sow and Reap for "AppendTo—like functionality") to build lists, not For and AppendTo—and it'll typically be easier than setting up a For-loop, since the iterated-over variable already behaves the way you want.

Your code also sets the global variable i; "good practice" would be to put it in the Module as well (if you were going to use it)!

Correct answer by thorimur on May 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP