2
$\begingroup$

I'm trying to get a list output, but I get integer results.

Is there a way to convert integers to a list?

Here is my code:

list = {12, 37, 44, 96};
list2 = IntegerDigits[list];
Do[
 list3 = Total[list2[[i]]];
 Print[list3];
 , {i, 1, Length[list]}]
$\endgroup$
2
$\begingroup$
Total /@ IntegerDigits[list]

{3, 10, 8, 15}

Also

Total[IntegerDigits[list], {2}] (* thanks: HenrikSchumacher *)
Total[Transpose@IntegerDigits[list]]
FromDigits[#, 1] & /@ IntegerDigits[list]

{3, 10, 8, 15}

$\endgroup$
  • 3
    $\begingroup$ Or Total[IntegerDigits[list], {2}]... $\endgroup$ – Henrik Schumacher Oct 27 '18 at 7:15
  • $\begingroup$ Thank you @HenrikSchumacher; i knew i was missing the most elegant form. $\endgroup$ – kglr Oct 27 '18 at 7:22
  • 1
    $\begingroup$ Tr /@ IntegerDigits[list] is actually a bit more efficient. :-) $\endgroup$ – Mr.Wizard Oct 27 '18 at 12:18
0
$\begingroup$

It does not improve on the previous solutions, but for such manipulations Table is normally enough. For the above lists,

Table[Total[list2[[i]]], {i, 1, Length[list]}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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