Namedtuples: some unexpected inconveniences

Deborah Swanson python at
Fri Apr 14 20:14:45 EDT 2017

MRAB wrote, on Friday, April 14, 2017 2:19 PM
> In the line:
>      values = {row[label] for row in group}
> 'group' is a list of records; row is a record (namedtuple).
> You can get the members of a namedtuple (also 'normal' tuple) by
> index, e.g. row[0], but the point of a namedtuple is that you can get 
> them by name, as an attribute, e.g. row.Location.
> As the name of the attribute isn't fixed, but passed by name, use 
> getattr(row, label) instead:
>      values = {getattr(row, label) for row in group}
> As for the values:
>      # Remove the missing value, if present.
>      values.discard('')
>      # There's only 1 value left, so fill in the empty places.
>      if len(values) == 1:
>          ...

Thanks for this, but honestly, I'm namedtupled-out at the moment and I
have several other projects I'd like to be working on. But I saved your
suggestion with ones that others have made, so I'll revisit yours again
when I come back for another look at namedtuples.

> The next point is that namedtuples, like normal tuples, are immutable.

> You can't change the value of an attribute.

No you can't, but you can use


to replace the value. Works just as well.

More information about the Python-list mailing list