Immutable Data Structures: Tuples
In the previous lesson, you stored your immutable data structures (
namedtuple) in an mutable one (
list). Now, you’ll see how you can replace that list with a tuple, which is like a list but immutable:
import collections Scientist = collections.namedtuple('Scientist', [ 'name', 'field', 'born', 'nobel', ]) scientists = ( Scientist(name='Ada Lovelace', field='math', born=1815, nobel=False), Scientist(name='Emmy Noether', field='math', born=1882, nobel=False), Scientist(name='Marie Curie', field='math', born=1867, nobel=True), Scientist(name='Tu Youyou', field='physics', born=1930, nobel=True), Scientist(name='Ada Yonath', field='chemistry', born=1939, nobel=True), Scientist(name='Vera Rubin', field='chemistry', born=1928, nobel=False), Scientist(name='Sally Ride', field='physics', born=1951, nobel=False), )
Now, you can access all of your data by index, but you’re no longer in danger of tampering with it. That’s exactly what you want to have when you’re taking a functional programming approach with a data set!
What I have now is I have a tuple of
Scientist objects. Previously, I had a list of dictionary objects. And so now, we’ve solved this immutability problem, I think, because now with this list of scientists I have now, I cannot go in there. I can’t delete anything.
That would be an immutable array of these
Scientist objects that are immutable, themselves, so the whole thing is immutable. In a perfect world, this is where you want to be if you’re doing any kind of functional programming in Python.
01:36 You want to start with a solid data structure that ideally is immutable. I mean, you know, you’re going to see in the examples that we’ll work through in the following videos, that you could totally do the same thing with dictionaries that are mutable or lists, but I think there’s a big benefit for thinking about how you can keep your data structures immutable if you’re trying to work with a functional programming style.
I hope you can start to see why this is useful. It’s going to become more obvious as we work through the other examples, but this is kind of the lead in to the other things that we’re going to cover next. So, what we’re going to look at next is a couple of functional programming primitives like the
filter() function, the
map() function, and the
reduce() function and how those correspond to some other things that are actually built into Python, like list comprehensions.
02:33 This won’t be like a full-on, “Oh, this is how you should do all of your programs from now on in Python,” but it’ll more be like a fun dive into functional programming, so you can get some inspiration to maybe see how you can apply that style in your own programs. All right, I’ll see you there. Happy Pythoning!
Become a Member to join the conversation.