10.1. Powerful Language Constructs

Python is a very expressive programming language. You can perform complex operations with just a few lines of code. In many cases, compact expressions translate to easy readability and efficient processing, thus these forms are often preferred over lengthier ones. Luckily, Python invites you to write clean and simple code once you know the nuances of the language. As a matter of fact, the following language constructs are the bread and butter of elegant Python.

10.1.1. List Comprehensions

As seen in the previous chapters, many tasks boil down to various operations on lists. Python provides a compact syntax for constructing new lists, called list comprehensions. Using list comprehensions you can construct a new list either from scratch or based on a previous sequence of objects.

Using a simple loop, you can construct a list of ten user names as follows

a = []
for x in range(10):
    a.append("user%d" % x)

However, you can get the same result with a list comprehension using only one line of code (as shown in Example 101).

Example 10.1. List comprehension
a = ["user%d" % x for x in range(10)]

Not only is this expression shorter, but it is also more efficient since we don't have to call the append() function ten times. List comprehensions have the following syntax:

[<list item expression> for <iterator variable> in <list expression>
    (if <conditional>)]

In Example 101, the list item expression is "user%d"% x, the iterator variable is x and the list ...

Get Mobile Python: Rapid Prototyping of Applications on the Mobile Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.