#### Overview of this book

IPython Notebook Essentials
Credits
www.PacktPub.com
Preface
Free Chapter
A Tour of the IPython Notebook
The Notebook Interface
Graphics with matplotlib
Handling Data with pandas
Advanced Computing with SciPy, Numba, and NumbaPro
IPython Notebook Reference Card
A Brief Review of Python
NumPy Arrays
Index

## Sequence types

Python sequence types are used to represent ordered collections of objects. They are classified into mutable and immutable sequence types. Here, we will only discuss `lists` (mutable) and `tuples` and `strings` (both immutable). Other sequence types are mentioned at the end of this section.

### Lists

The following example shows how to construct a list in Python and assign it to a variable:

```numbers = [0, 1.2, 234259399992, 4+3j]
```

Individual entries in the list are accessed with index notation as follows:

```numbers[2]
```

Notice that indexing always starts with `0`. Negative indices are allowed and they represent positions starting at the end of the list. For example, `numbers[-1]` is the last entry, `numbers[-2]` is the next-to-last entry, and so forth.

Since lists are a mutable sequence type, we are allowed to modify the entries in-place:

```numbers[0] = -3
numbers[2] += numbers[0]
print numbers
```

Another important way to refer to elements in a Python sequence type is slices, which allow the extraction of sublists from a list. Since this topic is very important for `NumPy` arrays, we defer the discussion to Appendix C, NumPy Arrays.

Python lists have a nice set of features, a few of which are illustrated in the following code examples:

• To find the length of a list, use the following command:

```len(numbers)
```
• To reverse a list in place, use the following command:

```numbers.reverse()
print numbers
```
• To append a new element, use the following command:

```numbers.append(35)
print numbers
```
• To sort the list in-place, use the following command:

```values = [1.2, 0.5, -3.4, 12.6, 3.5]
values.sort()
print values
values.sort(reverse=True)
print values
```
• To insert a value at a position, use the following command:

```values.insert(3, 6.8)
print values
```
• To extend a list, use the following command:

```values.extend([7,8,9])
print values
```

Python has a few handy ways to construct frequently used lists. The `range()` function returns a list of equally spaced integers. The simplest form returns a list of successive integers starting at `0`:

```range(10)
```

The preceding command returns the following list:

```[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```

Note that the last element is one less than the argument given in the function call. The rule of thumb is that `range(n)` returns a list with `n` elements starting at zero so that the last element is `n-1`. To start at a nonzero value, use the two-argument version as follows:

```range(3, 17)
```

A third argument specifies an increment. The following command line produces a list of all positive multiples of 6 that are less than 100:

```range(6,100,6)
```

Negative increments can also be used:

```range(20, 2, -3)
```

Lists support concatenation, which is represented by the `+` operator:

```l1 = range(1, 10)
l2 = range(10, 0, -1)
l3 = l1 + l2
print l3
```

### Note

Note that for the `NumPy` arrays, the `+` operator is redefined to represent vector/matrix addition.

The multiplication operator (`*`) can be used to construct a list by repeating the elements of a given list, as follows:

```l4 = 3*[4,-1,5]
print l4
```

The most flexible way to construct a list in Python is to use a list comprehension. A full discussion is beyond the scope of this appendix, but the following examples illustrate some of the possibilities:

• To display the list of the squares of the integers from `0` to `10` (inclusive), use the following command line:

```[n ** 2 for n in range(11)]
```
• To display the list of divisors of an integer, use the following command lines:

```k = 60
[d for d in range(1, k+1) if k % d == 0]
```
• To display the list of prime numbers up to 100, use the following command line (very inefficient):

```[k for k in range(2,101) if len([d for d in range(1, k+1) if k % d == 0])==2]
```
• To display the list of tuples of points with integers coordinates and their distances to the origin, use the following command line:

```[(i,j,(i*i+j*j)**0.5) for i in range(5) for j in range(6)]
```

### Tuples

Tuples are similar to lists, but are immutable—once created, their elements cannot

be changed. The following command lines will result in an error message:

```t1 = (2,3,5,7)
t1[2] = -4
```

Tuples have a few specialized uses in Python. They can be used as indexes in dictionaries (because they are immutable). They also consist of the mechanism that Python uses to return more than one value from a function. For example, the built-in function `divmod()` returns both the integer quotient and remainder in a tuple:

```divmod(213, 43)
```

Tuples support the same sequence interface as lists, except for methods that would modify the tuple. For example, there is no method named `sort()` that sorts a tuple in place.

### Strings

A Python string represents an immutable sequence of characters. There are two string types: `str`, representing ASCII strings, and `unicode`, representing Unicode strings.

A string literal is a sequence of characters enclosed by either single quotes or double quotes, as follows:

```s1 = 'I am a string'
s2 = "I am a string"
print s1
print s2
```

There is no semantic difference between single quotes and double quotes, except that a single-quoted string can contain double quotes and a double quoted string can contain single quotes. For example, the following command lines are correct:

```s3 = "I'm a string"
print s3
```

Strings are used for two main purposes: as dictionary indexes and to print messages. When printing messages, strings have the `format()` method that allows easy display of information. We use this feature frequently to add annotations to graphics. Here is an example:

```n = 3
message = 'The square root of {:d} is approximately {:8.5f}.'.format(n, n ** 0.5)
print message
```

In the preceding example, there are two format specifiers:

• `{:d}`: This specifies a decimal format for an integer value

• `{:8.5f}`: This specifies a field of width `8` and `5` decimals for a floating-point value

The format specifications are matched (in order) with the arguments, in this case `n` and `n ** 0.5`.

Strings have a rich interface. If you need to code something with strings, it is very likely that there is a built-in function that does the job with very little modification. A list of all available string methods, as well as formatting features, is available at https://docs.python.org/2/library/stdtypes.html#string-methods.