I am new to Python and I am learning it by reading the book “Head first Python“.
And my doubt is, when I want to print the nested list I am not getting the correct output as shown in the book
movies = [“The Holy Grail”, 1975, “Terry Jones & Terry Gilliam”, 91, [“Graham Chapman”, [“Michael Palin”, “John Cleese”, “Terry Gilliam”, “Eric Idle”, “Terry Jones”]]]
—
(Code given in book)
>>> for each_item in movies:
if isinstance(each_item, list):
for nested_item in each_item:
if isinstance(nested_item, list):
for deeper_item in nested_item:
print(deeper_item)
else:
print(nested_item)
else:
print(each_item)
—
(Output in book)
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
Graham Chapman
Michael Palin
John Cleese
Terry Gilliam
Eric Idle
Terry Jones
—
(But I got the below output only)
Graham Chapman
Michael Palin
John Cleese
Terry Gilliam
Eric Idle
Terry Jones
['Graham Chapman', ['Michael Palin', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']]
—
Please help me, I have tried everything i could think of. Thanks in advance.
The code as shown will not run because of an indentation error. The first if statement should be indented.
(If you got the result you have shown, you probably cut and pasted it without adjusting the indentation on this website).
works for me when pasted after the Python prompt. Your output is what you get when you have the final two lines indent 4 spaces less than this.
The print(nested_item) is also indented only 3 spaces where the rest (when indented) uses 4 spaces.