[Tutor] Lists in lists

Kent Johnson kent37 at tds.net
Sat Sep 16 23:31:22 CEST 2006


Morten Juhl Johansen wrote:
> # Newbie warning
> I am making a timeline program. It is fairly simple.
> I base it on appending lists to a list.
> Ex.
> [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]]
> 
> This seemed like a brilliant idea when I did it. It is easy to sort.

It's a fine idea

> Now, if I want to OUTPUT it, how do I indicate that I want to extract
> first entry in a list in a list? How do I print the separate entries?

There are a couple of things to do. First, at the top level, you have a 
list and you want to process each element of the list. A for loop works 
well for this; it assigns each member of the list in turn to a named 
variable:

In [2]: events=[[1863, "headline1", "event text1"], [1992, "headline2", 
"event text2"]]

In [3]: for event in events:
    ...:     print event
    ...:
    ...:
[1863, 'headline1', 'event text1']
[1992, 'headline2', 'event text2']

Within the for loop the variable 'event' contains a simple list which 
can be accessed with normal subscripting:
In [5]: for event in events:
    ...:     print 'In', event[0], event[1], event[2]
    ...:
    ...:
In 1863 headline1 event text1
In 1992 headline2 event text2

It's handy to assign names to the individual elements of the list. A 
variable named 'year' is a lot easier to understand than 'event[0]'. 
This is easy to do with tuple unpacking:

In [6]: for event in events:
    ...:     year, head, text = event
    ...:     print 'In', year, head, text
    ...:
    ...:
In 1863 headline1 event text1
In 1992 headline2 event text2


One final note - in Python it is more idiomatic - or at least closer to 
the intentions of the language designer - to use tuples for lists of 
dissimilar items. So it is a bit more idiomatic to express your initial 
list as a list of tuples:

events=[(1863, "headline1", "event text1"), (1992, "headline2", "event 
text2")]

It's not a big deal and it won't change the rest of the code at all, 
it's just a stylistic note.

Kent



More information about the Tutor mailing list