Mutable Collection Types
00:00 Previously, you saw how passing the mutable objects of custom classes to functions in Python mimics pass by reference. In this lesson, you’ll look at how passing mutable collection type objects does so as well. Recall that sets, lists, and dictionaries are mutable objects in Python.
00:19 This means you can modify them in place as opposed to creating new objects and rebinding variable names. So you can create a list, use an index to look at specific elements, and even change individual elements.
01:21 access individual elements using an index, but you can’t change an element using an index. Same thing for strings. You can create a string, access individual characters using an index, but you cannot modify individual characters.
So, for example, you can write a function which takes a dictionary as an argument and modify it in place, which is just like using pass by reference. Here’s a function that takes a dictionary as a parameter, then squares the value associated with the key
And here’s a script similar to all the ones you’ve seen before. We create a dictionary which maps
4, pass that dictionary as an argument to the
square() function, which will find the
4 and square it, and then we will print the result to see that that value has actually been squared.
Alternatively, you could write a function that squares in place the first element of a list. Pass a list as a parameter, access the first entry, the one with index
0, multiply it by itself and save it back to that same position.
Become a Member to join the conversation.