Vinz
Vinz

Reputation: 131

Python: Print new lines for each item in list

My list contains dates and each time after the date in the same sub-list.

[['2017-01-01', ['List 0', 'List 1', 'List 2']], ['2017-01-02', ['List 0', 'List 1', 'List 2']], ['2017-01-03', ['List 0', 'List 1', 'List 2']], 

I want to make a print statement, which prints for each date a new line and for each item in the sub-list a new line like this:

like in the screenshot

I tried several things, for example:

def printList(self):
        print(*self.dataList, sep='\n')

which prints a new line for each date but I want also a new line for each item in the sublist.

Upvotes: 3

Views: 680

Answers (1)

linusg
linusg

Reputation: 6429

Give pprint from the standard library a try:

import pprint

dataList = [['2017-01-01', ['List 0', 'List 1', 'List 2']], ['2017-01-02', ['List 0', 'List 1', 'List 2']], ['2017-01-03', ['List 0', 'List 1', 'List 2']]]
pprint.pprint(dataList, width=30)

Result:

[['2017-01-01',
  ['List 0',
   'List 1',
   'List 2']],
 ['2017-01-02',
  ['List 0',
   'List 1',
   'List 2']],
 ['2017-01-03',
  ['List 0',
   'List 1',
   'List 2']]]

You may need to play with the width parameter. Also see pprint.pformat().

Upvotes: 2

Related Questions