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:25 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. deal() reuses the shared-iterator trick from the start of the course.
00:38 It makes a list with hand_size references to one iterator over the deck. Each pass takes num_hands cards with islice(), which is one round. zip() then turns those rounds into hands.
00:52 Deal three hands of five cards.
00:56 Here’s the first player’s hand. And the deck now holds thirty-seven cards. The fifteen dealt cards were consumed from the cards iterator, which is exactly what you want in a game.
01:08 chain() has a class method called from_iterable(). It takes one iterable of iterables and chains them together. So it flattens a list of lists.
01:21 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:35 Take the same list of lists, and unpack each sublist with a star inside a comprehension.
01:43 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:53 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:06 In this lesson, you dealt hands from your shuffled and cut deck, and you flattened lists in two ways. Next up, you’ll leave the card table and work with real data: seventy years of daily prices from the S and P 500.
Become a Member to join the conversation.