Stack Overflow is full of questions where the answer is to create a "multidict", a dict mapping each key to a list of values.

There are two ways to do this, using defaultdict, or using a regular dict with setdefault. And as soon as someone posts an answer using one or the other, someone else suggests they should have used the other in a comment, and sometimes it even devolves into an argument about which is better.

Compare these two functions:

def f1(pairs): d = {} for key, value in pairs: d.setdefault(key, []).append(value) return d def f2(pairs): d = collections.defaultdict(list) for key, value in csv.reader(f): d[key].append(value) return d

It's hard to argue that either one is unclear, overly verbose, hard to understand, etc.
1

The problem

Often, using an iterator lazily is better than generating a sequence (like the one you get from a list comprehension). For example, compare these two scripts:

The first one has to read the entire file into memory, which can be a problem for huge files, but usually you don't have files that big.

A more serious problem is that it has to read the entire file before it can do any work.
2

A lot of people—not just novices—mix up parameters and arguments, especially when it comes to things like how default-valued parameters and keyword arguments, or argument unpacking and variable parameters.

The FAQ has a section called What is the difference between arguments and parameters, which explains the basics:

Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it.
3

How grouper works

A very common question on StackOverflow is: "How do I split a sequence into evenly-sized chunks?"

If it's actually a sequence, rather than an arbitrary iterable, you can do this with slicing. But the itertools documentation has a nifty way to do it completely generally, with a recipe called grouper.

As soon as someone sees the recipe, they know how to use it, and it solves their problem. But, even though it's very short and simple, most people don't understand how it works.
1
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.