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

Steven D'Aprano steve at pearwood.info
Tue Jul 13 02:40:21 CEST 2010


On Tue, 13 Jul 2010 08:19:51 am Siren Saren wrote:
> I'm still fairly new to programming.
[...]

Please don't include the ENTIRE 300+ lines of the digest in your post. 
Start a NEW email, don't reply to the digest, and if you absolutely 
have to reply to the digest, delete the parts that you are not directly 
replying to.

> I've seen a lot of examples in books for dealing with lists of
> alternating data types, but what about a list that doesn't follow a
> simple numeric pattern?  

The general solution to that is, avoid it.


[...]
> Probably easier to choose one of these.  So pretend I have a list
> like this:
>
> (Crime and punishment, page 10, page 40, page 30, Brother's
> Karamazov, page 22, page 55, page 9000, Father's and Sons, page 100,
> Anna Karenina, page 1, page 2, page 4, page 7, page 9)

The simplest way to deal with that is to put the pages into sub-lists, 
and combine the title and pages into a tuple:

booklist = [
 ("Crime and punishment", [10, 40, 30]),
 ("Brother's Karamazov", [22, 55, 9000]),  # That's a big book!
 ("Father's and Sons", [100]),
 ("Anna Karenina", [1, 2, 4, 7, 9]),
]

Now you can iterate over the collection:

for title, pages in booklist:
    print title
    for page in pages:
        print "page", page


or do whatever other work you need on them. Notice that the outer list 
is now easy to work with: every element of the outer list is the same, 
a tuple of two items. The inner lists are also easy to deal with: every 
element is simply a page number.

An alternative is a dictionary:

books = {
 "Crime and punishment": [10, 40, 30],
 "Brother's Karamazov": [22, 55, 9000],
 "Father's and Sons": [100],
 "Anna Karenina": [1, 2, 4, 7, 9],
 "Where's Wally?": [],
}

Now each key is simply the title, and the value is a list of page 
numbers.


-- 
Steven D'Aprano


More information about the Tutor mailing list