Dennisboys
Dennisboys

Reputation: 583

How to control the format of this list printing function

I would like a print function that can print inner list.

The expected result of my function should be:

a
b
    aa
    bb
         aaa
         bbb

However, now the result is: (the added space is not expected)

a
b
        aa
        bb
            aaa
            bbb

How can I get the expected result? I have tried my best but failed to figure out a solution. Thanks in advance for any helpers.

testlist = ["a","b",["aa","bb",["aaa","bbb"]]]

add_space = False

def printList(the_list, level):

    global add_space

    for each_item in the_list:
        if isinstance(each_item, list):
            add_space = True
            level += 1
            printList(each_item, level)
        else:
            if add_space == True:
                for numbers in range(level):
                    print("\t",end="")
            print(each_item)


printList(testlist,1)

Upvotes: 0

Views: 73

Answers (3)

Ronald Oussoren
Ronald Oussoren

Reputation: 2810

Global state (the add_space variable) isn't necessary here when the first call to printList is done with level 0 (e.g. printList(testlist, 0)). That simplifies the code and makes it easier to test and debug.

When you add a print statement for the level to your code you'll also see that the level ends up as 2 for the first list item.

And a final small bug: your code increases the level variable when 'each_item' is a list, but doesn't decrease it afterwards. Because of this the indentation will be wrong when you add a new item at the end of the list, just passing level+1 to the recursive call to printList fixes that issue.

Combining all of this:

testlist = ["a","b",["aa","bb",["aaa","bbb"]]]

def printList(the_list, level):

    for each_item in the_list:
        if isinstance(each_item, list):
            printList(each_item, level + 1)
        else:
            for numbers in range(level):
                print("\t",end="")
            print(each_item)


printList(testlist,0)

Upvotes: 1

ATOzTOA
ATOzTOA

Reputation: 35950

Just call the method as

printList(testlist,0)

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43447

Using a recursive method.

testlist = ["a", "b", ["aa", "bb", ["aaa", "bbb"]]]

def recursive_list_print(lst, level=0):
    for item in lst:
        if isinstance(item, list):
            recursive_list_print(item, level+1)
        else:
            print('{}{}'.format('\t'*level, item))

recursive_list_print(testlist)

Yields:

>>> 
a
b
    aa
    bb
        aaa
        bbb

Upvotes: 3

Related Questions