Typefully

itertools.takewhile()

Avatar

Share

 • 

4 years ago

 • 

View on X

itertools.takewhile() one of those good-to-know-about-functions I decided to explore it today… Read on if you've not come across takewhile before… 👇🪡🧵 #Python #coding #100daysofcode
takewhile takes successive items from a sequence for as long as a certain condition is true. It's the equivalent of using a _while_ loop to _take_ successive items from the sequence until the while condition is not met–hence the name takewhile.
In this example, the challenge is to see how many successive heads I can get when I flip a coin…
In the first attempt there's a list of heads and tails. In this one, there are three heads at the start of the list. The result from takewhile gives three heads…
In the second part, we repeat this several times using a generator. You can see the outputs range from some cases with no heads at all, and others with varying number of heads. One of the tries even had 5 consecutive heads… #coinflip #coding #itertools
You can read the unrolled version of this thread here: typefully.com/s_gruppetta_ct/XEgP3M6
Avatar

Stephen Gruppetta

@s_gruppetta_ct

Constantly looking for innovative ways to talk and write about Python • Mentoring learners • Writing about Python • Writing about technical writing