Skip to main content
abarnert's user avatar
abarnert's user avatar
abarnert's user avatar
abarnert
  • Member for 13 years, 1 month
  • Last seen more than a month ago
Stats
363,518
reputation
58.8m
reached
6,316
answers
5
questions
Loading…
About

Some people, when confronted with a problem, think "I know, I'll use itertools."

Now they have next(takewhile(not_, count())) problems.


Since I've been asked about this multiple times now:

It's a reference to "Now they have two problems" about regular expressions. next(takewhile(not_, count())) is guaranteed to give you 0, and pretty efficiently… but it's not exactly readable. Which is the joke. itertools does solve all your problems, but you don't always need to use it.

If you don't grasp the paradigm, go read David Beazley's presentations. Once you do: "I've got a CSV, and I want to group the rows by…" Pass a csv.reader to groupby. "I've got a bunch of values, and I want to take them 4 at a time and…" Use grouper from the recipes. "I've got a file, and I want to take each pair of adjacent lines and…" tee it, next one copy, and zip them. And so on.

But of course some problems have an even easier solution, and once you start thinking in terms of sequences of transformations on iterators, sometimes you'll miss the easier answer.

(The exact same thing happens with numpy, of course.)

53
gold badges
620
silver badges
688
bronze badges
31,816
Score
6,027
Posts
95
Posts %
4,497
Score
621
Posts
10
Posts %
2,013
Score
455
Posts
7
Posts %
1,590
Score
190
Posts
3
Posts %
1,580
Score
330
Posts
5
Posts %
1,495
Score
185
Posts
3
Posts %
Top posts
View all questions, answers, and articles