0
$\begingroup$

I have a huge list = {l1, l2, l3, ...}, which I want to output by labeled rows. My attempt was to

Do[Print["list[i]:"];Print[list[i]], {i, 1, Length[list]}]

Which is not working very well. I would like to know how i can "label" every line of my output like so:

list[1] = l1
list[2] = l2
list[3] = l3
...
$\endgroup$
  • $\begingroup$ If your Do loop only exist to create the formatted output and does nothing else, you could consider replacing it with something like Transpose[{Defer@list /@ Range[Length@list], ConstantArray["=", Length@list], list}] // Grid or Table[{"list[", i, "] = ", list[[i]]}, {i, Length@list}] // TableForm[#, TableSpacing -> {1, 0}] &. $\endgroup$ – Karsten 7. Jun 8 '17 at 10:46
2
$\begingroup$

Does this do what you had in mind?

Do[Print["list[", i, "] = ", list[[i]]], {i, 1, Length[list]}]
$\endgroup$
  • $\begingroup$ Far easier than expected! Thanks a lot! I did not know about the comma separated chaining within Print[expr, expr, ...] $\endgroup$ – Knowledge Jun 8 '17 at 10:05
0
$\begingroup$

You should use StringTemplate.

fmt = StringTemplate["list[``] = ``"];
Do[Print[fmt[i, lst[[i]]]], {i, 1, Length[lst]}]

This is still ugly: it creates a cell for every call to Print. You say the list is "huge" (justifying Do), but then you want to print it. Hmm; perhaps it is not so huge? If you don't mind using a bit more memory, the following is conceptually cleaner.

strings = MapIndexed[fmt[First@#2, #1] &, lst];
Print@StringRiffle[strings, "\n"]
$\endgroup$
  • $\begingroup$ Actually it is not that "huge" but to huge for me to type out every line by hand ;) $\endgroup$ – Knowledge Jun 9 '17 at 5:51
0
$\begingroup$

You could use Dataset to create an easy-to-read output of your list. Dataset handles very large outputs really well:

Dataset[AssociationThread[Range[Length[list]] -> 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.