Keeping track of things with dictionaries

Chris Angelico rosuav at gmail.com
Tue Apr 8 05:34:24 EDT 2014


On Tue, Apr 8, 2014 at 7:28 PM, Frank Millman <frank at chagford.com> wrote:
> Are you saying that
>
>     all([len(word) == 23 for word in words_by_length[23]])  # hope I got
> that right
>
> will not return True?

That'll return true. What it won't show, though, is the length of the
word as you would understand it in the English language. You see, when
you iterate over a file, you get strings that include a newline at the
end, and that'll be included in the length :) So with a dictionary of
English words, you'll see that "cat\n" is a four-letter word, and
"python\n" is a seven-letter word. It's a subtle point, but an
important one when you start looking at lengths of things that are
suddenly off by one.

Obviously the solution is to strip them, but I didn't want to pollute
the example with that (nor a 'with' block). I didn't think it
particularly important, and just acknowledged the bug in what I
thought was a throw-away line :)

ChrisA



More information about the Python-list mailing list