-1

n = [1, [2, [3, [4, 5]]], [6, [7, [8, [9]], 10]]]

In python, I want to write a nested function within the function 'print_list' that calls itself recursively for each sub-list. The nested function should have an additional parameter indent which keeps track of the indentation for each recursion level. when implementing print_list(n), it prints a nested list 'n' in the following format

print_list(n)

.1

.....2

.........3

.............4

.............5

.....6

.........7

.............8

2 Answers2

0

I have a bad feeling I am doing your homework.. Anyways.. Make sure you understand the code..

n = [1, [2, [3, [4, 5]]], [6, [7, [8, [9]], 10]]]

def reqprint(inputdata, depth=0):

    if isinstance(inputdata, list):
        for sublist in inputdata:
            reqprint(sublist, depth=depth+1)
    else:
        print('.' * depth + str(inputdata))

reqprint(n)

when run

.1
..2
...3
....4
....5
..6
...7
....8
.....9
...10
brunsgaard
  • 5,066
  • 2
  • 16
  • 15
0
import pprint

n = [1, [2, [3, [4, 5]]], [6, [7, [8, [9]], 10]], 11]


def printList(list_name, level = 0):
    for sub_element in list_name:
        if isinstance(sub_element, list):
            printList(sub_element, level+4)
        else:
            print '.' * level + str(sub_element)

printList(n)
pprint.pprint(n, width=4)

>>> ================================ RESTART ================================
>>> 
1
....2
........3
............4
............5
....6
........7
............8
................9
........10
11
[1,
 [2,
  [3,
   [4,
    5]]],
 [6,
  [7,
   [8,
    [9]],
   10]],
 11]
>>>