Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

2.9. List comprehensions

A comprehension is a compact notation for describing operations on sets or sequences of items (like lists). You may already know it from ordinary mathematical set notation, where, for example, {x | x ϵ N, x > 0} is read as “all values x such that x comes from the natural numbers (denoted by N), and x is greater than zero”—in other words, all positive natural numbers.

If you’re not already familiar with set notation, take a close look at this example, and you’ll quickly see how it works. The vertical bar | separates the template part, which describes how the individual elements are made up, from the generators and conditions part that specifies what the sources for elements are and what restrictions you have. In this example, the template is x, you have a generator that says “for all values x in N,” and a condition that only those x that are greater than zero may be part of the result. Pretty simple stuff, really, but it’s an efficient way of expressing these kinds of operations.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial