# Tutorial by Examples

## List Comprehensions

A list comprehension creates a new list by applying an expression to each element of an iterable. The most basic form is: [ &lt;expression&gt; for &lt;element&gt; in &lt;iterable&gt; ] There's also an optional 'if' condition: [ &lt;expression&gt; for &lt;element&gt; in &lt;iterable&gt; if &lt;c...

## Dictionary Comprehensions

A dictionary comprehension is similar to a list comprehension except that it produces a dictionary object instead of a list. A basic example: Python 2.x2.7 {x: x * x for x in (1, 2, 3, 4)} # Out: {1: 1, 2: 4, 3: 9, 4: 16} which is just another way of writing: dict((x, x * x) for x in (1, 2...

## Generator Expressions

Generator expressions are very similar to list comprehensions. The main difference is that it does not create a full set of results at once; it creates a generator object which can then be iterated over. For instance, see the difference in the following code: # list comprehension [x**2 for x in r...

## Set Comprehensions

Set comprehension is similar to list and dictionary comprehension, but it produces a set, which is an unordered collection of unique elements. Python 2.x2.7 # A set containing every value in range(5): {x for x in range(5)} # Out: {0, 1, 2, 3, 4} # A set of even numbers between 1 and 10: {x f...

## Avoid repetitive and expensive operations using conditional clause

Consider the below list comprehension: &gt;&gt;&gt; def f(x): ... import time ... time.sleep(.1) # Simulate expensive function ... return x**2 &gt;&gt;&gt; [f(x) for x in range(1000) if f(x) &gt; 10] [16, 25, 36, ...] This results in two calls to f(x) for 1,000 values of...

## Comprehensions involving tuples

The for clause of a list comprehension can specify more than one variable: [x + y for x, y in [(1, 2), (3, 4), (5, 6)]] # Out: [3, 7, 11] [x + y for x, y in zip([1, 3, 5], [2, 4, 6])] # Out: [3, 7, 11] This is just like regular for loops: for x, y in [(1,2), (3,4), (5,6)]: print(x+y) ...

## Counting Occurrences Using Comprehension

When we want to count the number of items in an iterable, that meet some condition, we can use comprehension to produce an idiomatic syntax: # Count the numbers in `range(1000)` that are even and contain the digit `9`: print (sum( 1 for x in range(1000) if x % 2 == 0 and '9' in str...

## Changing Types in a List

Quantitative data is often read in as strings that must be converted to numeric types before processing. The types of all list items can be converted with either a List Comprehension or the map() function. # Convert a list of strings to integers. items = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,...

Page 1 of 1