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: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.
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.
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
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,
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.
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.field, and so on.
Become a Member to join the conversation.