Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Dealing Hands and Flattening Lists
00:00
In this lesson, you’ll deal hands from your deck with tools you already know, and then you’ll flatten a list of lists lazily with chain() and eagerly with a new feature from Python 3.15.
00:12 Dealing works like this: with three players and five cards each, you take one card for every player at a time. The first round gives each player a card, then the second round does the same, and so on for five rounds.
00:24
If you collect each round as a tuple, then each player’s hand is one column. Turning rows into columns is exactly what zip() does.
00:34
deal() reuses the shared iterator trick from the start of the course. It makes a list with hand_size references to one iterator over the deck.
00:43
Each pass takes num_hands cards with islice(), which is one round. zip() then turns those rounds into hands. Deal three hands of five cards.
00:55
Here’s the first player’s hand. And the deck now holds 37 cards. The 15 dealt cards were consumed from the cards iterator, which is exactly what you want in a game. chain() has a class method called .from_iterable().
01:11 It takes one iterable of iterables and chains them together, so it flattens a list of lists.
01:20
Its input doesn’t have to be finite. Chaining an endless repeat() of a string gives you the same thing as cycle(). If you only need a new list, then Python 3.15 offers a second option.
01:34
Take the same list of lists and unpack each sublist with a star inside a comprehension. Both approaches flatten, but they behave differently. chain.from_iterable() stays lazy, so it’s the one to reach for when the result feeds into another iterator.
01:52
It’s also the opposite of batched(). The comprehension builds the whole list in memory, which is fine when a list is what you want. Remember that comprehension unpacking needs Python 3.15 or later.
02:04 In this lesson, you dealt hands from your shuffled and cut deck, and you flattened lists in two ways. Next up, you leave the card table and work with real data: 70 years of daily prices from the S&P 500.
Become a Member to join the conversation.