-2

How can I pretty-print a (possibly nested) Python list with indices, similar to the Perl's Data::Printer module, e.g. for L = ['a', 'b', None, 'c'] the output should be something like this:

[
    [0] 'a',
    [1] 'b',
    [2] None,
    [3] 'c',
]
planetp
  • 14,248
  • 20
  • 86
  • 160

1 Answers1

1

you can use enumerate to get the indices, and use pprint to pretty-print a python list. For example:

pprint.pprint([{num: value} for num, value in enumerate(L)], width=20)

and the output is:

[{0: 'a'},
 {1: 'b'},
 {2: None},
 {3: 'c'}]
ZoeLiao
  • 92
  • 3
  • You can flatten the nested lists before using enumerate and pprint https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists – ZoeLiao Feb 06 '19 at 16:47