The syntax is [expression for item in sequence] where:
# Example: creating a list of perfect squares
# The expression i**2 is applied to every element i to generate the new list
squares = [i**2 for i in range(1, 11)]
print squares
The syntax is [expression for item in sequence if condition] where:
# The condition is i % 2 == 0
# This only includes the even integers
[i**2 for i in range(1, 11) if i % 2 == 0]
# Import all the array functions
from numpy import *
# A one-dimensional array can be created directly from a list using the "array" function
a = array([1, 2, 3])
# An array is displayed as follows
a
# A one-dimensional array prints like a list, but without the commas
print a
# Adding a scalar to an array adds the scalar to every element
print a + 3
# Assignment operators can be applied to arrays, just as with scalars
a *= 3
print a
# All basic mathematical operations can be applied directly to arrays.
# The resulting array is generated by applying the operation to each element individually
print a**2
# Complicated mathematical expressions can be built up from simpler ones
print a**2 + 3*a + 1
# Importing numpy imports array versions of all the basic trigonometric and transcendental functions.
print exp(a)
# Operations involving two arrays are performed on corresponding elements in each array
# This is similar to vector addition and subtraction, but extends to all mathematical operations
a = array([1, 2, 3])
b = array([4, 5, 6])
c = a + b
print c
# ones(n) creates an array of n 1's
ones(5)
# zeros(n) creates an array of n 0's
zeros(4)
# empty(n) creates an uninitialized array of length n
empty(6)
# <array>.copy() creates a copy of <array>
a.copy()
# arange(start, stop, step) is an array version of range
# However, arange can also take floats as arguments, whereas range is restricted to integers
arange(2.2, 6, .5)
# linspace(start, stop, n) creates an array of n equally-spaced points in the interval [start, stop]
# Both endpoints are included by default
linspace(0, 1, 11)
%pylab inline
# Functions can be quickly plotted using linspace
# "plot" takes arrays as arguments as well as lists
x = linspace(0, 20, 201)
y = sin(x)
plot(x, y)
# Choosing too few points to plot produces a jagged graph
x = linspace(0, 20, 21)
y = sin(x)
plot(x, y)
Note: %%timeit must be the first line in the cell
%%timeit
tmax = 500
tmin = tmax/2
b_values = linspace(0, 4, 41)
for b in b_values:
x = 0.5
for i in xrange(tmax):
if i > tmin:
plot(b, x, 'r.')
x = b*(1 - x)*x
The same code as above, but updating a vector of x-values in parallel instead of using a "for" loop. The vectorized code runs nearly 50 times faster.
%%timeit
tmax = 500
tmin = tmax/2
b = linspace(0, 4, 41)
x = 0.5
for i in xrange(tmax):
if i > tmin:
plot(b, x, 'r.')
x = b*(1 - x)*x
# Creating a two-dimensional array from a list of lists (of equal length)
# Note that arrays are printed with spaces between items and no commas
a = array([[1,2,3], [4,5,6]])
print a
# Arrays have a "shape", which is a tuple of the number of elements in each axis (dimension)
a.shape
# The "dtype" of an array is the data type of the elements stored
# Since the original list contained all integers, the dtype is 64-bit integer ('int64')
a.dtype
# Arrays can be created by passing a shape tuple into zeros, ones, or empty
# The default type when creating arrays is a float
b = ones((3,4))
print b
# To change the data type, use the "dtype" keyword
b = ones((3,4), dtype=int)
print b
# We can also create arrays of booleans
# False corresponds to zero and True to one
b = ones((3,4), dtype=bool)
print b
# "arange" creates a one-dimensional array
a = arange(20)
print a
# Arrays can be "reshaped" to any shape with the same number of elements
a = arange(20).reshape((4, 5))
print a
# Arrays use zero-based indexing, like lists
# A single element can be accessed by specifying its position on each axis
# For a two-dimensional array, these can be thought of as a (row, column) pair
# So, to access the element in row 1 and column 2
a[1,2]
# Array elements can be assigned using the "=" operator
a[1,2] = 100
print a
# Setting this element back to 7 again
a[1,2] = 7
print a
# To slice the first row, just use the row index
print a[0]
# To slice every element from the first column, we need to select from every row, column index 0
# The ":" means select everything along this axis
print a[:,0]
# A start:stop:step filter can be applied to each axis independently
# So, to select rows 1-2 and columns 1-3
print a[1:3, 1:4]
# To select each row and every second column
print a[:, ::2]
# Using rational numbers, arithmetic on non-integers can be done exactly
# However, there can be a price to pay in terms of memory requirements
from fractions import Fraction
# Running the mayfly model using rational numbers
# At time t, the denominator is 2^(2^(t + 1) - 1). So, the number of bits needed is 2^(t + 1) - 1
# => size of the denominator increases exponentially with time, making exact arithmetic infeasible
b = Fraction(7, 2)
x = Fraction(1, 2)
for t in range(8):
print t, x
x = b*(1-x)*x