[Tutor] Request for help learning the right way to deal with listsin lists

Alan Gauld alan.gauld at btinternet.com
Tue Jul 13 09:35:45 CEST 2010

"Siren Saren" <siren99 at yahoo.com> wrote
> say I have a list that's a composite of two elements:
> books and key pages / albums and favorite tracks /
> medicines and times taken, whatever.

Thats a good scenario for using a dictionary containing
a list or tuple per key.

> To make a program that does something to the
> first set of elements based on the second set of elements,

I'm not quite sure what you mean by this though...?

> if I am planning to, for example, tear out these key
> pages and make a wall hanging. Am I right to think
> that I want to get them into a form that clearly relates
> them to each other from the outset?

Yes, you should always try to find a data structure that
reflects the problem. It will naturally lead to simpler algorithms
and cleaner code.

> Does a dictionary make sense-- I've read that I should
> expect to put a lot of my data into dictionaries?

Yes a dictionary is a good structure for random lookups
based on a unique key that returns related data.

> a. Make a sublist of the Books.

You don't need a sublist, just use the dictionary.

> b. Look each up book in the main list to get an index values

You don't need index values, just use the dictionary directly.

> For book in Books:
> A dictionary should map the book to a list of all the elements
> in the main list that fall between the book's index value and
> the next book's index value

The dictionary returns the list of pages directly.

> I keep coming up with embedded loops to express this
> but I simultaneously feel like I am missing a third layer

You need a loop over the dictionary and possibly a loop over the 

for book, pages in Books.items():
    print book
    for page in pages:
         print 'page: ', page

If the data gets more complex you could put the data into a class:

class Book:
      def __init__(self, title, pages=[]):
          self.title = title
          self.pages = pages

Books = [ Book('War & Peace", [3,56,88]),
               Book("Huck Finn", [2,5,19]) ]

for book in Books:
     print book.title, book.pages

Thre are many options, you need to decide which best suits your 


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list