Exploring Custom Sequences and Mappings
00:00 In this lesson, you’ll explore how you can implement your own custom sequences and mappings in Python. These are powerful tools that let you create objects that behave like lists, tuples, or dictionaries, but with your own custom behavior and rules.
00:17 Before customizing them, let’s first understand what sequences and mappings actually are.
00:25 A sequence in Python is a collection of items where the order matters. Each item has a specific position and you can access them using an index.
00:35 Sequences let you do things like looping over them, slicing to get a portion of the sequence, and checking the length. Here are some familiar examples: lists, tuples, and strings.
00:52 Now, a mapping is a collection of key-value pairs where the order doesn’t necessarily matter. Instead of accessing items by position, you use a unique key to look up its corresponding value.
01:06
Mappings are perfect for storing data that you want to retrieve using specific labels rather than by position. Some examples are dictionaries and the defaultdict
specialized dictionary from the collections
module that automatically provides a default value for a key that doesn’t exist yet.
01:28
This is a subclass of the built-in dict
class.
01:32
When you want to create a custom sequence or mapping, you need to follow the sequence and mapping protocol and implement the following magic methods. The __getitem__
magic method accesses an item by its index, like sequence[index]
.
01:52
Next is the __len__
magic method, which you explored before. It gets the number of items with the len()
function. You also need the __contains__
magic method that checks if an item is in the sequence with in
or not in
.
02:09
And lastly, you’ll need a __reversed__
magic method implementation, which helps you get a reversed version of the sequence with the reversed()
function.
Become a Member to join the conversation.