CARVIEW |
Head First Python contains examples of Python's list comprehension technology, which is a technique that lets me take code like this:
new_list = [] for thing in some_list: new_list.append(do_something(thing))
and turn it into shorter code, like this:
new_list = [do_something(thing) for thing in some_list]
Note that both code fragments assume the existence of a list called some_list and a function called do_something(). List comprehensions are an example of Python's functional programming facilities, whereas the three lines of "standard code" are an example of Python's imperative programming facilities. Both work, of course and - depending on your point of view, one technique may appeal to you over the other.
I'm a big fan of the "less code is better" principle, in that I firmly believe the number of bugs in my code is directly related to the number of lines of code I write. Any technique that lets me write less code always gets a big thumbs-up from me, and using list comprehensions lets me write less code. To illustrate, let's take a real-world example of where using a list comprehension can have a dramatic impact.
Imagine I've designed a web application that has a HTML form element that allows my users to select an age from a drop down list. I'm building my web application using the popular Django web framework, which has lots of built-in goodness for dynamically creating HTML. In fact, Django can dynamically generate a HTML form directly from a model definition, which is way cool. When I use code like this to define my data model, Django takes it and dynamically generates a form:
from django.db import models class StudentData(models.Model): name = models.CharField(max_length=50, verbose_name="Student's Name") age = models.IntegerField(verbose_name="Student's Age")
As well as the self-explanatory arguments to the field definitions, there's also an argument called choices which allows me to specify a list of tuples which Django will use to restrict the input values allowed. If I create a list like this:
_ALLOWED_AGES = [(4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), (11, '11'), (12, '12'), (13, '13'), (14, '14'), (15, '13'), (16, '16'), (17, '17'), (18, '18')]
I can then change my model definition for age to look like this:
age = models.IntegerField(verbose_name="Student's Age", choices=_ALLOWED_AGES)
Django will now use this list to create a HTML drop-down list within the form. The first element in each tuple is the value stored in the model, whereas the second element is displayed within the form's drop-down list. Pretty easy, eh?
Well... yes, it it easy... but, look at all that extra code. Count the lines added: 9. That's nine places where I could potentially introduce an error into my code. Remember: more code means more errors. Did you notice that I have a typo in the string-value associated with 15? It is incorrectly coded as '13', not '15'? Hard to spot, isn't it?
Let's improve things--and by improve I mean "reduce the possibility of error"--by writing some code to generate the list, instead of simply defining it. I'll start with an empty list which I then populate with the generated tuples using a standard for loop:
_ALLOWED_AGES = [] for each in range(4,19): _ALLOWED_AGES.append((each, str(each)))
Which gets me down to 3 lines of code, which isn't bad. Of course, I can rewrite this using a list comprehension:
_ALLOWED_AGES = [(each, str(each)) for each in range(4,19)]
Which gets me down to just 1 line of code, which I think is pretty cool.
Now, ask yourself this question: which would you rather maintain? Nine lines of code, three lines of code or just one line of code?
To conclude, and to shamelessly paraphrase a famous Canadian singer/songwriter: Less code is better. Bumper stickers should be issued!
Posted by Paul Barry on Tuesday, May 10 Permalink | Comments (7)
By now, this study (PDF) by a team of psychology researchers from Princeton and Indiana University has stirred up some interesting press (and plenty of "I knew it" nodding of heads amongst the Head First team) given the unusual results. Students asked to memorize relatively foreign material (characteristics of "aliens") performed better on recall tests if they were presented the study materials in fonts like Comic Sans (a font we often take a lot of flak for using in our books), which is notoriously harder to read than a more traditional font like Arial. The differentiators weren't size or formatting like bolding or italics, but rather the difficulty of reading the font itself.
One of the study authors, Daniel M. Oppenheimer, recently said in the New York Times, "The reason that the unusual fonts are effective is that it causes us to think more deeply about the material. Think of it this way, you can't skim material in a hard to read font, so putting text in a hard-to-read font will force you to read more carefully."
The implications for Head First books is almost comically clear (apologies). Often you may note that we reinforce key teaching points on a page in a big, funky font. We use Comic Sans, and we're not afraid to admit it. It turns out we're not just admirers of (potentially otherwise) bad fonts. There's some real cognitive science method to our madness.
I found one other interesting nugget related to this result in that same NYT article (which I originally thought was just going to be a rehash of the font study results). It quoted a series of experiments conducted in 1996 by researchers at Macalester College and New York University who were interested in whether prior exposure to answers for an exam would indeed positively impact student's performance on exams. Not that surprisingly, they found a positive correlation. But they found something even more interesting along the way--the nature of the preparatory information had an even more profound impact. To wit:
"In one experiment, researchers found that participants studying a difficult chapter on the industrial uses of microbes remembered more when they were given a poor outline -- which they had to rework to match the material -- than a more accurate one."
Now we're not suggesting that we give you "poor" material when it comes to Head First, but we do let you screw up occasionally. And we do so on purpose. Finding something that isn't working and figuring out why proves to be a far more compelling (and successful) learning strategy than just being handed the answers up front.
Would you agree? Are our bad fonts and FUBAR moments part of what makes Head First work well for you?
Posted by Courtney Nash on Monday, Apr 18 Permalink | Comments (3)
Well, it's clear that blogging hasn't been a big priority for the Head First team this year, but we're back with some great news. We're testing out a new online course format with Head First WordPress, which was released this past summer.
It's called Head First WordPress in Tandem. As most Head First fans will know, we think of our readers as learners--people who are actively along for the ride while learning about a given topic, not just passive butts in seats in a boring classrom. This new online course format is based on the same principles.
Over the course of three weeks, you'll receive an email at the start of each day with an assignment based on a chapter (or two) in Head First Wordpress. Then at the end of the week on Friday, we'll host an hour-long live Q&A; with author Jeff Siarto, who will work through the examples with everyone, tackling any trouble spots people ran into, or delving into more complex topics and ideas if time allows.
It starts on Monday, November 29, and the price is $49.99. The course cost includes a PDF of Head First WordPress. (If you already have Head First WordPress, then we'll offer you any other Head First PDF of your choice instead.)
We're really excited about this new avenue for Head First, and hope you'll join us for the class.
Posted by Courtney Nash on Wednesday, Nov 17 Permalink | Comments (5)



Looking for source files, code, exercise answers, and other materials to go along with your Head First book? Go to this page, find your book on the list, and click on the title.




Head First Algebra, Head First PHP & MySQL, Head First Rails, and Head First Web Design are now available.
Buy 2 Books, Get the 3rd FREE! Use the discount code OPC10 when you buy direct from O'Reilly.


Want to reinforce what you've learned? Like a hands-on style? The O'Reilly School of Technology offers online courses in variety of technical topics.
Stay up on all the latest Head First news, tips, and special offers with the Head First Newsletter.



Head First Physics, Head First Statistics, and Head First Algebra are now available.
Buy 2 Books, Get the 3rd FREE! Use the discount code OPC10 when you buy direct from O'Reilly.

-
Head First Ajax
Chapter 7
Chapter 1 Excerpt
Head First Algebra
Chapter 4
Head First C#
Chapter 5
Chapter 4 Excerpt
Chapter 7 Excerpt
Head First Design Patterns
Chapter 3
Head First HTML with CSS & XHTML
Chapter 8
Head First Java, 2nd Edition
Chapter 2
Chapter 8
Head First JavaScript
Chapter 2
Head First Object-Oriented Analysis & Design
Chapter 3
Head First PMP
Chapter 11
Free Practice Exam
Critical Path Drill
Head First PHP & MySQL
Chapter 7
Chapter 5 Excerpt
Head First Physics
Chapter 4
Head First Rails
Chapter 8
Head First Servlets & JSP, 2nd Edition
Chapter 9
Head First Software Development
Chapter 6
Head First SQL
Chapter 1
Chapter 7 Excerpt
Chapter 8 Excerpt
Head First Statistics
Chapter 4
Head First Web Design
Chapter 8
Contact the Webmaster | Get the Newsletter
? 2010, O'Reilly Media, Inc. | (707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on HeadFirstLabs.com are
the property of their respective owners.