The (Scientist's) Python Inferno
This is a brief description of some of the common stumbling points in Python for scientific programmers, named in deference to The R Iferno (which is much more expansive).
Table of Contents
- Indexing starts at 0, not 1
- Dividing one integer by another yeilds an integer (Python 2 only)
- Some methods change an object in place and return None
Indexing starts at 0 not 1
If you want the first item in a list, string, tuple, etc. then the index for this value is 0. For example,
This is standard for practically all serious programming languages.
Integer Division (Python 2.x)
Dividing an integer by another integer returns an integer, even when the two numbers are not evenly divisible. For example,
Any decimal portion is simple removed. This happens because computers pay attention to the type of data they are working with and often like to maintain types when combining two things of the same type. However, since this result is clearly wrong to most humans (and to all scientists) Python 3 now does this division as expected. There are three approaches to fix this integer division problem:
- Import the expected functionality by typing from __future__ import division at the beginning of an interactive session or at the beginning of your script.
- Convert one or more of the integers to floats prior to doing the calculation: float(2) / 3
- Add a decimal place to one of the integers so that it's type is already float: 2 / 3.0. Note that this does actually work very well programmatically so approaches (1) and (2) are preferred.
Methods return None
Methods are functions that are attached to objects of a particular type. Some of these methods return modified versions of the object and do not change the object itself, but some modify the object and return None. For example, all lists have a method called sort that sorts the values in the list. When you call sort it sorts the list in question and returns None. So,
Misunderstanding this behavior can lead to a common bug when attempting to sort a list where the values in the list are accidentally delected:

