Sequence Protocol with __getitem__ in Python

Level 4164 keystrokes

Implements __len__ and __getitem__ so a class works with len(), indexing and list().

Python code

1class Deck:
2 cards = ["A", "K", "Q"]
# len(d) calls __len__ and returns 3
3 def __len__(self):
4 return len(self.cards)
# d[i] calls __getitem__; list() also uses it, asking for index 0, 1, 2 until IndexError
5 def __getitem__(self, i):
6 return self.cards[i]
7d = Deck()
# Prints 3 A ['A', 'K', 'Q']
8print(len(d), d[0], list(d))

Output

3 A ['A', 'K', 'Q']
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 8
  • (× 7
  • )× 7
  • "× 6
  • ,× 5
  • :× 3
  • [× 3
  • ]× 3
  • .× 2
  • =× 2

More Python examples at level 4

← Python typing practice