Page 55 -
P. 55
meet python
Creating a list that contains another list is straightforward. But what happens when you try to process a list that
contains another list (or lists) using the for loop from earlier in this chapter?
Let’s use IDLE to work out what happens. Begin by creating the list of the movie data for “The Holy Grail” in
memory, display it on screen, and then process the list with your for loop:
>>> movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91,
["Graham Chapman", ["Michael Palin", "John Cleese",
"Terry Gilliam", "Eric Idle", "Terry Jones"]]]
>>> print(movies)
['The Holy Grail', 1975, 'Terry Jones & Terry Gilliam', 91, ['Graham Chapman', ['Michael Palin',
'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']]]
The list within a list within
>>> for each_item in movies:
print(each_item) a list has been created in
memory.
The Holy Grail
1975 The “for” loop prints each item of
Terry Jones & Terry Gilliam the outer loop ONLY.
91
['Graham Chapman', ['Michael Palin', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']]
The inner list within the inner list is printed “as-is.”
Your for loop is working OK. I think the
trouble is that you haven’t told it what to
do with any inner lists that it finds, so it
just prints everything, right?
Yes, that’s correct: the loop code isn’t complete.
At the moment, the code within the loop simply prints each list
item, and when it finds a list at a slot, it simply displays the entire
list on screen. After all, the inner list is just another list item as far as
the outer enclosing list is concerned. What’s we need here is some
mechanism to spot that an item in a list is in fact another list and take
the appropriate action.
That sounds a little tricky. But can Python help?
you are here 4 19