Using namedtuples field names for column indices in a list of lists

Erik python at
Mon Jan 9 20:47:00 EST 2017

On 10/01/17 00:54, Deborah Swanson wrote:
> Since I won't change the order of the records again after the sort, I'm
> using
> records.sort(key=operator.attrgetter("Description", "Date"))
> once, which also works perfectly.
> So both sorted() and sort() can be used to sort namedtuples.  Good to
> know!

As people keep saying, the object you have called 'records' is a *list* 
of namedtuple objects. It is not a namedtuple.

IIRC, you create it using a list comprehension which creates the 
records. A list comprehension always creates a list.

The sorted() function and the list.sort() method can be used to sort a 
list containing any objects - it's just a case of telling them how to 
obtain the key values to compare (which, in the case of simple attribute 
access which the namedtuple objects allow, "operator.attrgetter()" will 
do that). This is why sorting the list works for you.

You could sort objects of different types - but you might need to supply 
a function instead of operator.attrgetter() which looks at the type of 
each object and returns something that's obtained differently for each 
type (but which the sort function can compare).

When you say 'Foo = namedtuple("Foo", "spam ham")', you are creating a 
"factory" which is able to generate "Foo" objects for you.

When you say "x = Foo(1, 2)" you are using the factory to create an 
object for you which has its "spam" and "ham" attributes set to the 
values 1 and 2 respectively.

When you say "records = [Foo(x, y) for x, y in some_iterable()]", you 
are creating a list of such objects. This is the thing you are then sorting.

Does that make sense?

Regards, E.

More information about the Python-list mailing list