Locked learning resources

You must own this product to watch this lesson.

Locked learning resources

You must own this product to watch this lesson.

Writing Clean, Pythonic Code With namedtuple (Summary)

This lesson is from the Real Python video course by Christopher Trudeau.

00:00 In the previous lesson, I showed you how to create a subclass based on a named tuple. In this lesson, I’ll summarize the course. Named tuples make your code more readable than their non-named associates, and memory-wise have identical footprints.

00:15 You create a named tuple using the namedtuple() factory found in the collections module. The factory takes a string containing the name of the class you want to create and the names of the attributes in the tuple.

00:27 You can specify the attribute names in a space- or comma-delimited string or by using an iterable. The factory has optional arguments for turning on automatic field renaming, specifying default values, or altering the module name associated with the created class. Named tuples can make your code more readable by being specific about the parts of a tuple through dot notation by making functions that return multiple values more explicit, reducing the number of arguments to a function, or grouping associated attributes of a chunk of data together.

01:03 Generally, named tuples take up less memory than most other data structures and have faster construction times than everything else except regular tuples.

01:12 They are immutable, though. If the program you’re writing needs the data to change, they might not be the best choice.

01:20 For more information on named tuples, visit the most excellent Python docs. If you’re thinking about understanding your code’s memory footprint, the pympler library is a useful profiling tool.

01:33 Or if you’re interested in the speed part of performance, this article shows you different ways of measuring that.

01:40 For more information on tuples and other data structures, you can dig further into some Real Python content. This first article compares lists and tuples and is available as both a written tutorial and a video course, or if you want to go real deep on Python data structures, this guide is exhaustive, so much so the corresponding video course comes in three parts.

02:05 Thanks for your attention. I hope you enjoyed the course.

You must own this product to join the conversation.