The Python Data model through code snippets

Python
Author

Quasar

Published

November 21, 2025

A pythonic card deck

import collections

Card = collections.namedtuple('Card',['rank','suit'])

class FrenchDeck:
    ranks = [str(n) for n in range(2,11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, position):
        return self._cards[position]

We can use a namedtuple to build classes of objects that are just bundles of attributes with no custom methods, like a database record. In the example, we use it to provide a nice representation for the cards in the deck, as shown in the console session below:

beer_card = Card('7', 'diamonds')
beer_card
Card(rank='7', suit='diamonds')

The point of this example is actually the FrenchDeck class. FrenchDeck is a sequence. We can access a card by its position and we can iterate through the FrenchDeck.

deck = FrenchDeck()
deck[0]
Card(rank='2', suit='spades')
for card in deck[:5]:
    print(card)
Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
Card(rank='4', suit='spades')
Card(rank='5', suit='spades')
Card(rank='6', suit='spades')

We can also pick a random card using the random module from the standard library.

import random

random.choice(deck)
Card(rank='10', suit='diamonds')

Its easier to benefit from the rich Python standard library and avoid reinventing the wheekl like the random.choice() function.

How about sorting cards? A common system of ranking cards is by rank(with aces being highest) and then by suit in the order of spades