# Null being added to every element in list list

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}

• How about: Table[StringPart[word, StringLength[word] - i + 1], {i, StringLength[word]}] May 1 at 22:53
• StringTake[word, {-1, 1, -1}]
– ciao
May 1 at 23:15

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)!

• Also note f[word_]:=Characters@StringReverse@word. (+1) May 1 at 23:01
• @Edmund definitely! OP mentioned they were trying to do it without StringReverse though—but similarly, one can technically use f[word_] := Reverse@Characters[word], though this also might be out of the spirit of the exercise I presume OP is doing to gain familiarity with Mathematica 🙃 May 1 at 23:09
• Thank you! I know java and python, so definitely more familiar with loops. This was helpful, I'm trying to get more familiar with Mathematica. May 3 at 6:07