0

I am using Python. Given a list, I want to print the contents of all the sublists in the original list. So, for instance, if I have a list:

L = ["0", ["(1,0)"], ["(2,0)", ["(2,1,0)", ["(2,1,1,0)"], ["(2,1,1,1)"]]], ["(3,0)"]]

Then I want my output to be:

0
(1,0)
(2,0)
(2,1,0)
(2,2,2,0)
(2,1,1,1)
(3,0)

Now, I have used the following code:

def Print_Nested_List(s):
a = 0
for a in range(len(s)):
    if type(s[a]) != type([]):
        print(s[a])
    else:
        b = 0
        for b in range(len(s[a])):
            Print_Nested_List(s[a])
L = ["0", ["(1,0)"], ["(2,0)", ["(2,1,0)", ["(2,1,1,0)"], ["(2,1,1,1)"]]], ["(3,0)"]]
Print_Nested_List(L)

I get the following output:

0
(1,0)
(2,0)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(2,0)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(3,0)

Clearly, you can see that although all the contents are printed, some stuff is printed multiple times.

Now, why is this happening and how can I fix my code?

Note: I am just a noob at coding and any help would be great. Is there a better way of doing this? Thanks a lot in advance:)

deadshot
  • 8,881
  • 4
  • 20
  • 39
MathWiz
  • 115
  • 3
  • 1
    [how-to-make-a-flat-list-out-of-list-of-lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Patrick Artner Sep 13 '20 at 12:20
  • 1
    Others have already given several suggestions for working code, but as a hint to why your code does not work: What is the variable `b` for? Where is it used? – Ture Pålsson Sep 13 '20 at 12:26

2 Answers2

2

Use isinstance for checking type if it is list use a for loop and and call method recursively on each element of the list.

def print_list(lst):
    if isinstance(lst, list):
        for x in lst:
            print_list(x)
    else:
        print(lst)

print_list(L)

Output:

0
(1,0)
(2,0)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(3,0)
deadshot
  • 8,881
  • 4
  • 20
  • 39
1

You can use recursion here.

def recurse_(lst):
    for i in lst:
        if isinstance(i, list):
            recurse_(i)
        else:
            print(i)

recurse_(L)

0
(1,0)
(2,0)
(2,1,0)
(2,1,1,0)
(2,1,1,1)
(3,0)
sushanth
  • 8,275
  • 3
  • 17
  • 28