Page 58 -
P. 58
list the list
Here’s a copy of the current list-processing code. Your task was to rewrite this code using an if
statement and the isinstance() BIF to process a list that displays another list.
for each_item in movies:
print(each_item)
Process the “movies”
list as before. The inner loop
for each_item in movies: needs a new target
You need to check if the if isinstance(each_item, list): identifier.
current item is a list.
If it is a list, use another for nested_item in each_item:
“for” loop to process the
nested list. print(nested_item)
else: If the current item
isn’t a list, display it
Did you manage to get your print(each_item) of the enclosing list
indentation right?
on screen.
Let’s use IDLE to see if this code makes a difference to the output displayed on screen:
>>> for each_item in movies:
if isinstance(each_item, list):
for nested_item in each_item:
print(nested_item)
else:
print(each_item)
This is a little better, but not by
The Holy Grail much…there’s another nested list here
1975 that’s not being processed properly.
Terry Jones & Terry Gilliam
91
Graham Chapman
[‘Michael Palin’, ‘John Cleese’, ‘Terry Gilliam’, ‘Eric Idle’, ‘Terry Jones’]
22 Chapter 1