Iterating over the list of all combinations between elements of a list

The Issue

Did you ever had to compare all elements of a list and you had this ugly code:

for elem_1 in my_list:
	for elem_2 in my_list:
		if elem_1 != elem_2:
			# Do Stuff

We’re near the 80 character limit before even starting to write the main code.

The Solution:

Use itertools.combinations(iterable, r). It’s a function that creates tuples with length r (e.g. (x,x) for r=2, (x,x,x) for r=3 …).

from itertools import combinations
for (elem_1, elem_2) in combinations(my_list,2):
	# Do stuff

Blessed be the negative programmer!

Testing and debugging using IPython

The Issue

One issue I always had when debugging with IPython was the need to reload all my modules each time I make a change. It would be nice if modules could be reloaded automatically each time before running a command.

The Solution:

Use autoreload, an IPython extension which automatically reloads modules before executing each line.

To use it run IPython the following commands:

%load_ext autoreload
 
# Reloads all modules (except those excluded by %aimport) every time before executing the code
%autoreload 2

# Mark module 'module_foo' to not be autoreloaded
%aimport -module_foo

import my_class

my_function()
# outputs 1
# Let's say I change the code to make it the function returns 2

my_function()
# outputs 2

Now you can easily test each part of your implementation in IPython online and with no trouble at all.