November 8, 2015

1441 words 7 mins read

Python Tutorial

Python Tutorial

Python basic tutorial covering: Python Review, Numpy, SciPy and Matplotlib. The material is mainly based on Python Numpy Tutorial.

Python Tutorial:

Python Review - Basic Data Types


  • Integers and floats work as you would expect from other languages
  • Does not have unary increment (x++) or decrement (x–) operators
  • Other: built-in types for long integers and complex numbers


Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.):


String objects have a lot of useful methods.

Python Review - Container Types

Python includes several built-in container types: lists, dictionaries, sets, and tuples.


A list is the Python equivalent of an array, but is resizeable and can contain elements of different types.

  • Lists - Slicing: In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing
  • Lists - Looping: You can loop over the elements of a list. If you want access to the index of each element within the body of a loop, use the built-in enumerate function.
  • Lists - List Comprehensions: When programming, frequently we want to transform one type of data into another -> LC. List comprehensions can also contain conditions.


A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript.

  • Dicts - Looping: It is easy to iterate over the keys in a dictionary. If you want access to keys and their corresponding values, use the iteritems method.
  • Dicts - Dictionary Comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries.


A set is an unordered collection of distinct elements.

  • Sets - Looping: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set.
  • Sets - Set Comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions.


A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list.

One of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot.

Python Review - Functions & Classes

Python functions are defined using the def keyword. We will often define functions to take optional keyword arguments. The syntax for defining classes in Python is straightforward.


Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object (MATLAB style), and tools for working with these arrays.


  • A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers.
  • The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.
  • We can initialize numpy arrays from nested Python lists, and access elements using square brackets.
  • Numpy also provides many functions to create arrays.

Array Indexing - Slicing

Numpy offers several ways to index into arrays. Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array.

Array Indexing - Slicing

You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing.

Array Indexing - Integer Array Indexing

When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array.

Array Indexing - Boolean Array Indexing

Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition.


Every numpy array is a grid of elements of the same type.

Numpy provides a large set of numeric datatypes that you can use to construct arrays.

Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype.

Array Math

Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module

Note that unlike MATLAB, * is elementwise multiplication, not matrix multiplication.

We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices.

dot is available both as a function in the numpy module and as an instance method of array objects.

Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum.

Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays.

The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object.


Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations.

Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.

For example, suppose that we want to add a constant vector to each row of a matrix …

This works… however when the matrix x is very large, computing an explicit loop in Python could be slow.

Note that adding the vector v to each row of the matrix x is equivalent to forming a matrix vv by stacking multiple copies of v vertically, then performing elementwise summation of x and vv.

Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting.

The line y = x + v works even though x has shape (4, 3) and v has shape (3,) due to broadcasting.

This line works as if v actually had shape (4, 3), where each row was a copy of v, and the sum was performed elementwise.

Broadcasting two arrays together follows these rules:

  • If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
  • The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
  • The arrays can be broadcast together if they are compatible in all dimensions.
  • After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
  • In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension.

Functions that support broadcasting are known as universal functions.

Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible.


Numpy provides a high-performance multidimensional array and basic tools to compute with and manipulate these arrays.

SciPy builds on this, and provides a large number of functions that operate on numpy arrays and are useful for different types of scientific and engineering applications.

Image Operations

SciPy provides some basic functions to work with images.

For example, it has functions to read images from disk into numpy arrays, to write numpy arrays to disk as images, and to resize images.


The functions and allow you to read and write MATLAB files.

Distance between Points

SciPy defines some useful functions for computing distances between sets of points.

The function scipy.spatial.distance.pdist computes the distance between all pairs of points in a given set.

A similar function (scipy.spatial.distance.cdist) computes the distance between all pairs across two sets of points.


Matplotlib is a plotting library.

In this section give a brief introduction to the matplotlib.pyplot module, which provides a plotting system similar to that of MATLAB.


The most important function in matplotlib is plot, which allows you to plot 2D data.

With just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels.


You can plot different things in the same figure using the subplot function.


You can use the imshow function to show images.

comments powered by Disqus