Loading video player…

Danger Zone: Mixing Mutable and Immutable Data Structures

In this lesson, you’ll see that using a combination of mutable and immutable data structures can still lead to problems. Even if you use an immutable data structure like namedtuple, you still run the risk of modifying your data set if you store your immutable data structures in mutables ones, like lists.

In the next lesson, you’ll see how to address this problem by replacing the rest of your mutables data structures with immutable ones.

Avatar image for Abby Jones

Abby Jones on July 24, 2019

If you pass the variables ada and emmy to the new list, you won’t need to use pprint because it prints out nicely.

Avatar image for felixthec

felixthec on Feb. 6, 2020

As a side note it is also a risk if you have an mutable data structure inside of immutable once.

from pprint import pprint
scientists = tuple([
...     {'name': 'Ada Lovelace', 'field': 'math', 'born': 1815, 'nobel': False},
...     {'name': 'Emmy Noether', 'field': 'math', 'born': 1882, 'nobel': False},
...     {'name': 'Marie Curie', 'field': 'physics', 'born': 1930, 'nobel': True},
... ])
del scientists[0]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
scientists[0]['name'] = 'Ed Lovelace'
({'born': 1815, 'field': 'math', 'name': 'Ed Lovelace', 'nobel': False},
 {'born': 1882, 'field': 'math', 'name': 'Emmy Noether', 'nobel': False},
 {'born': 1930, 'field': 'physics', 'name': 'Marie Curie', 'nobel': True})
Avatar image for Dan Bader

Dan Bader RP Team on Feb. 7, 2020

Good point @felixthec! Unfortunately there’s no immutable dictionary data type in the Python standard library, but something like Pysistence’s PDict data type would work well here.

Avatar image for Thomas Wilson

Thomas Wilson on March 27, 2020

Can you tell us what the repl is called you’re using in the courses?

Avatar image for jcandali

jcandali on March 27, 2020

It’s bpython

Become a Member to join the conversation.