Tutorial by Examples

A list comprehension creates a new list by applying an expression to each element of an iterable. The most basic form is: [ <expression> for <element> in <iterable> ] There's also an optional 'if' condition: [ <expression> for <element> in <iterable> if <c...
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 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 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...
Consider the below list comprehension: >>> def f(x): ... import time ... time.sleep(.1) # Simulate expensive function ... return x**2 >>> [f(x) for x in range(1000) if f(x) > 10] [16, 25, 36, ...] This results in two calls to f(x) for 1,000 values of...
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) ...
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...
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 = ["1","2","3",...

Page 1 of 1