Loading video player…

Immutable Data Structures: namedtuple

In this lesson, you’ll see some of the problems you could run into if you use mutable data structures to store your data set. Then, you’ll see how you can approach this data set with immutable data sctrutures.

You’ll learn how you can use .namedtuple() from the collections module, which is built into Python, in order to represent your data in an immutable data structure so it can’t be modified in-place.

00:00 Now, the other thing that I didn’t quite like about using dictionaries here for

00:07 this functional programming example is that—as you can see—I’m repeating a lot of the key names here. That isn’t perfect, because what if

00:17 I make a typo, right? What if I have a typo here and instead of calling this field "name", I call it "nime"?

00:26 I would just introduce a typo here. And in all the other fields, maybe they’re okay, and I didn’t do anything wrong here, and I would define another item, but I just made this typo.

00:41 There’s no validation. I can just do that, right? I can just create this object here. There’s no one double-checking my typing. I could just add that to this list, and there would be no guarantees that every item on this list would have the same properties. So that’s why I decided to go down a different route.

00:56 What we’ll do instead is we’re going to import the collections module, and then we’re going to define a Scientist object—or, I guess it’s a class—using the collections.namedtuple() function.

01:11 So here, we’re going to give this thing a name. This is going to be part of the docstring, and it’s going to be the typename, so you just want to duplicate that here just by convention, because this namedtuple() function can’t actually access the name you gave to the return value here.

01:28 So, we just need to duplicate this thing here. Then, we’re going to define a list of properties. And so here, okay, we need a 'name', we need the 'field',

01:40 we need the birthdate, and we need a flag for whether or not that person won the Nobel Prize. Then, we can close that function call. This is a factory function that will create a new namedtuple class.

01:57 Now, we have this thing here called Scientist. It has a bunch of fields on it and you can see here, these are exactly the fields that we were looking for earlier, and now I can create new Scientist instances. So here, I can say name='Ada Lovelace', I can say field equals—and you can already tell here that these are not just dictionary keys,

02:26 but these are actually keyword arguments that I’m passing to this function. I can’t really type and talk at the same time, but bear with me. So, I’m assigning these to the values I want here, and now, we’re going to create our first Scientist object. Right.

02:43 So you can see here, this sort of kind of prints one of these dictionary objects, but now it’s a real Scientist object. We can say ada equals the Scientist object, and then we can access the field. We can reach in here and can say ada.name, ada.field, and so on.

03:02 And the great thing is a namedtuple instance is actually immutable. So I cannot go in now and say, “Hey, we’re going rename 'Ada' to 'Ed'.

03:17 It doesn’t work like that. You can’t set an attribute on a namedtuple. So now that means we have a way to represent these individual items and to

03:30 create, to represent this data set in an immutable data structure. So, let’s do that.

Avatar image for MrMaul

MrMaul on Dec. 7, 2019

Which editor is being used in the video?

Avatar image for B S K Karthik

B S K Karthik on Feb. 27, 2020

Which IDE/Command prompt have you used.Can you please tell me.It looks good.

Avatar image for Dan Bader

Dan Bader RP Team on Feb. 27, 2020

I’m using an alternative Python REPL called bpython in my videos. You can learn more about it here: bpython-interpreter.org

Avatar image for B S K Karthik

B S K Karthik on Feb. 28, 2020

Thank you

Avatar image for Lokman

Lokman on March 26, 2020

Hi @Dan Bader, just wanna correct your article above collection.namedtulple to collection.namedtuple.

Avatar image for Dan Bader

Dan Bader RP Team on March 27, 2020

Thanks for catching my typo there, should be fixed now :)

Avatar image for elliekafubu

elliekafubu on March 28, 2020

is it possible to have a pdf of these wonderful lessons?

Avatar image for Choong Han

Choong Han on March 31, 2020

Hey, in the namedtuple function, what does the first index, scienctist represent

Avatar image for Varun Vaddiparty

Varun Vaddiparty on May 10, 2020

@Han It is the typename. collections.namedtuple returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable.

Avatar image for pavanala13433

pavanala13433 on July 6, 2020

hey i think we can change names of scientists using ada._replace(name=”xxx”) function so the named tuple is also mutable am i right once check the functionality of _replace function in namedtuple

Avatar image for pavanala13433

pavanala13433 on July 6, 2020

hey dan can you please respond to my commment

Avatar image for Geir Arne Hjelle

Geir Arne Hjelle RP Team on July 6, 2020


_replace() creates a new named tuple with certain values replaced. It does not mutate the original named tuple:

>>> from collections import namedtuple
>>> Point = namedtuple("Point", ["x", "y"])
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)

>>> p._replace(x=3)
Point(x=3, y=2)

>>> p
Point(x=1, y=2)
Avatar image for pavanala13433

pavanala13433 on July 6, 2020

Thank you very much sir @Geir Arne Hjelle for responding and cleared my doubt with your explanation.....

Avatar image for Jakob Fredriksson

Jakob Fredriksson on Aug. 1, 2020

Began learning how to code this spring and this course is a bless! I do like Dan’s teaching quite much as well (His courses on YouTube that made me a paying member on Real Python).

However. Since start, I haven’t liked OOP for some reason… Since I grasped the concept somewhat - in my case barely removed the dust from the box - I’ve all the time the feeling of “passing the river to collect water”. Guess I don’t understand the concept enough.

Gah, now I’m loosing the thread. My intension is NOT going into any OOP debate (understand it’s a thing). What do I know. I just wanted to point out this style of coding appeals more to me =)

Avatar image for Dan Bader

Dan Bader RP Team on Aug. 1, 2020

Thanks for your comment Jakob, glad to hear that :) The way I look at FP vs OOP is that they’re just different “tools in the tool box” and I try to pick whichever I find the most appropriate given the circumstances. And subjective appeal/enjoyment can be a great reason for choosing one style over another! (At least on hobby projects or projects that don’t have to stick to an already established architectural style.)

By the way, if you’re looking for resources to make Python OOP “click” then check out our Python OOP Learning Path here on Real Python!

Avatar image for Jakob Fredriksson

Jakob Fredriksson on Aug. 2, 2020

Thx for the link to RP’s OOP Learning Path. I will grind the whole thing during upcoming weeks. Btw, it must be written:

“Give me all the x:es where x is in scientists but only if x.nobel is True”. The way you commented between syntaxes while writing this finally made me confident with list comprehensions.

It’s fascinating how effective tiny details sometimes are =)

Become a Member to join the conversation.